抱歉,这是一个常见问题,但是我花了相当长的时间搜索答案,却找不到确切的答案。
我有一个抽象类,其中包含其他抽象类(的定义)的字段。然后将这些用于属性的具体实现。但是,当我想初始化该抽象类的实现时,我希望用这些字段的特定实现填充这些字段。甚至对于我自己来说,这听起来确实令人困惑,因此这里是示例。
// My main abstract class
public abstract class Log
{
public virtual bool AppendLog
{
set { _logWriter.Append = value; }
}
internal LogWriter _logWriter; //LogWriter is another abstract class
public abstract void AddEntry(string input);
}
// Implementation of abstract class
public class SyncLog : Log
{
public SyncLog
{
// Now I want to initialize LogWriter abstract class in parent with
// It's actual implementation SyncLogWriter : LogWriter
_logWriter = new SyncLogWriter();
}
public override void AddEntry(string input)
{
content.AddEntry(input);
_logWriter.Write("Hello");
}
}
尽管从技术上讲这是合规的,甚至可行,但是仍然存在问题。使用_logWriter时,我只能访问在抽象类LogWriter中声明的方法和属性,而不能访问在其子级(SyncLogWriter)中额外实现的方法和属性。虽然从技术上讲这很有意义,但我想知道是否有任何方法可以执行类似的方法,但是要使SyncLogWriter中所有可用的其他东西都可用吗?
最佳答案
在继承的类_syncLogWriter
上使用其他成员SyncLog
。
同样,最好通过构造函数为基类初始化_logWriter
成员并将其设为私有。
// My main abstract class
public abstract class Log
{
protected Log(LogWriter logWriter)
{
_logWriter = logWriter;
}
public virtual bool AppendLog
{
set { _logWriter.Append = value; }
}
private LogWriter _logWriter; //LogWriter is another abstract class
public abstract void AddEntry(string input);
}
// Implementation of abstract class
public class SyncLog : Log
{
private SyncLogWriter _syncLogWriter
public SyncLog() : this(new SyncLogWriter()) { }
private SyncLog(SyncLogWriter logWriter) : base(logWriter)
{
_syncLogWriter = logWriter;
}
public override void AddEntry(string input)
{
content.AddEntry(input);
_syncLogWriter.Write("Hello");
}
}