When designing Object Inheritance, the parent Object Construction sub-requires some parameters. These parameters can be provided by the sub-Object Construction sub-object through the base keyword.
Copy codeThe Code is 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> ()){}
}
}
However, if you want to use the parameter passed to the parent object as a sub-object, you need a little trick to get it. The first solution is to create a property object for the sub-object and pass it to the parent object. This method will soon fail, and compilation alone will fail ..... Object creation is to first run the constructor and then produce the object. In the sub-construction stage, the attributes of the object must be used, which must fail.
Copy codeThe Code is 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 and try to solve it from another angle. Simply create another sub-Object Construction sub-object, first create the object to be passed to the parent object, and then not directly pass to the parent Object Construction sub-object, but to the sub-object's own construction sub-object, then this constructor is passed to the parent object. I spent all my eyes, like a tongue twister ..... Let's look at the program code. In fact, it's quite simple to complete this small design:
Copy codeThe Code is 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;
}
}
}