Creating a child in the parent constructor

Is it possible to create an instance of a child using the parent constructor and pass it some parameter (in this case a string) to indicate the type of child that should be created?

+3
source share
3 answers

No. In C # you create an instance of a class, then the runtime calls its constructor. By the time the constructor runs too late to select a different type.

However, a constructor of a derived class always calls one of its base class constructors, and you can use it to your advantage (to avoid code repeating).

, , . , Parent, Child1:Parent Child2:Parent, factory :

public class ParentFactory {
    public Parent CreateParent(string type) {
        switch(type) {
            case "Child1":
                return new Child1();
            case "Child2":
                return new Child2();
            default:
                throw new ArgumentException("Unexpected type");
        }
    }
}
+8

, A B, A. new A("B"), B?

.

, , , , , .

http://msdn.microsoft.com/en-us/library/dex1ss7c.aspx

var obj = myAssembly.CreateInstance("myNamespace.myClassB");
+1

, , :)

public class parent:child
{
    private child childObj;
    public parent(string childName)
    {
        childObj = new child(childName);
    }

}
public class child
{
    private string name;

    public child(string _name)
    {
        name = _name;
    }
}
0

Source: https://habr.com/ru/post/1779421/


All Articles