When designing object inheritance, the parent object constructor requires parameters that can be provided through the base keyword by the child object constructor.
Copy Code code as follows:
Namespace Test001
{
public class ParentClass
{
Constructors
Public ParentClass (ienumerable<string> datacollection)
{
This. DataCollection = datacollection;
}
Properties
Public ienumerable<string> datacollection {get; private set;}
}
public class Childclass:parentclass
{
Constructors
Public ChildClass (): Base (new List<string> ()) {}
}
}
But if the child object, to use this parameter passed to the parent object, it needs a little skill to obtain. First of all, the idea is to create a Property object for the child object before passing it to the parent object. This method will soon fail, just compile it .... The object is created by first running the constructor and then giving birth to the object. At the stage of constructing a child, the object's properties must be used, which is a failure.
Copy Code code as follows:
Namespace Test002
{
public class ParentClass
{
Constructors
Public ParentClass (ienumerable<string> datacollection)
{
This. DataCollection = datacollection;
}
Properties
Public ienumerable<string> datacollection {get; private set;}
}
public class Childclass:parentclass
{
Fields
Private readonly list<string> _datacollection = new list<string> ();
Constructors
Private ChildClass (): Base (_datacollection) {}
}
}
Think about it, change the angle to solve this problem. Simply open another constructor of the child object, first establish the object to pass to the parent object, then not directly to the parent object's constructor, but to the child object's own constructor, and then the constructor is passed to the parent object. I wrote my eyes all spent, like tongue twisters ... Just look at the program code, it is quite simple to complete this small design:
Copy Code code as follows:
Namespace Test003
{
public class ParentClass
{
Constructors
Public ParentClass (ienumerable<string> datacollection)
{
This. DataCollection = datacollection;
}
Properties
Public ienumerable<string> datacollection {get; private set;}
}
public class Childclass:parentclass
{
Fields
Private readonly list<string> _datacollection = null;
Constructors
Public ChildClass (): This (new list<string> ()) {}
Private ChildClass (list<string> datacollection)
: Base (DataCollection)
{
_datacollection = datacollection;
}
}
}