我想为继承树中的所有类实现默认对象模式。我正在做如下所示。
namespace test
{
public class Record
{
public int ID { get; set; }
}
public class StudentRecord : Record
{
public string StudentID { get; set; }
}
public class DriverRecord : Record
{
public string DLNumber { get; set; }
}
public class client
{
public static void Main()
{
StudentRecord st = StudentRecord.Default;
DriverRecord dr = DriverRecord.Default;
}
}
}
我希望默认属性或方法将所有类级属性初始化为其默认值,我不想为每个类重复实现。我只想写在 Record (base) class 上。您能就此提出一些建议吗?
最佳答案
您正在寻找的正是构造函数的用途。构造函数可以调用继承的基础构造函数,因此您只需在一个地方进行基础初始化。有时基本功能确实可以满足您的需求:)
public class Record
{
public int ID { get; set; }
public Record()
{
// ... do general initialisation here ...
}
}
public class StudentRecord : Record
{
public string StudentID { get; set; }
public StudentRecord()
: base() // This calls the inherited Record constructor,
// so it does all the general initialisation
{
// ... do initialisations specific to StudentRecord here ...
}
}
public class client
{
public static void Main()
{
// This calls the constructor for StudentRecord, which
// in turn calls the constructor for Record.
StudentRecord st = new StudentRecord();
}
}
关于c# - 默认对象实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5537999/