Default object implementation
I want to implement default object pattern for my all classes in the inheritance tree. I am doing as shown below.
namespace test
{
public class Record
{
pu开发者_如何学JAVAblic 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;
}
}
}
I want the default property or method to initialize all the class level properties to their defaults and I don’t want to repeat the implementation for each class. I just want to write on Record (base ) class . Can you provide some suggestions on this?
What you’re looking for is exactly what constructors are for. A constructor can call an inherited base constructor, so you need to do the base initialisation in only one place. Sometimes the basic functionality really does what you need :)
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();
}
}
The Record
class can only set the properties which are inherited by StudentRecord
and DriverRecord
. If you want to set class-specific properties to their default values you have to override the method (I would make a method) and do something like this (for StudentRecord
):
public void override Initialize()
{
base.Reset();
this.StudentId = 0;
}
HTH
You don't have any "class level properties", i.e. static properties, in your code sample. The properties you do have (the instance properties) are already initialized to their defaults -- 0 for integers, null for references, etc.
If you want to define your own defaults -- perhaps ID should default to -1 until you save, and the strings should default to "" -- then that's exactly what constructors are for:
public class Record
{
public Record() { ID = -1; }
public int ID { get; set; }
}
public class StudentRecord : Record
{
public StudentRecord() { StudentID = ""; }
public string StudentID { get; set; }
}
// etc.
If you want something different from either of those, you'll have to explain what you're looking for.
I think Null Object Pattern is what you need.
精彩评论