C# Activator createInstance for extending class

笑着哭i 提交于 2020-01-16 00:58:07

问题


I have a base class, which is as follows:

public Data()
    {
        id = num++;
        SetVariables();
    }
    //fill every Variable varNames, parseInduction, noise, seperator in Children Classes
    public Data(String line)
    {
        //first declare all variables in sub classes
        if (id == 0)
            throw new NotSupportedException("You are not allowed to use this constructor for creating the first instance!");
        id = num++;
        SetVariables();
        parseLine(line);
    }

And i also have a Sub Class extending this Class.

class DienstGruppe : Data
{
    protected override void SetVariables(){
        varNames = new String[] {"id", "name"};
        parseInduction = "DienstGruppen = {";
        parseEnd = "};";
        beginOfDataLine = "<";
        endOfDataLine = ">";
        noise = new String[] { "\"" };
    }
}

And i try to create an object with the Activator.CreateInstance() Function as follows:

Data myData = (Data)Activator.CreateInstance(this.GetType(), new object[] { line });

Note: this.GetType() is used in a function of Data by the extending class, to get the Type of the current class.

But this causes a problem. Bizzarly i get an error, that the class (in my case DienstGruppe) does not have the constructor. I guess inheritance is not the same in c# as in java. So how can i solve this problem?

It works for "Data" though.

Regards, Dominik


回答1:


In addition to the answer by Pavel, which is correct about requiring a constructor with the appropriate signature in the child class, it may be worth pointing out why you need to do that.

In C#, constructors are not inherited, as per Section 1.6.7.1 of the C# Language Specification.

Unlike other members, instance constructors are not inherited, and a class has no instance constructors other than those actually declared in the class. If no instance constructor is supplied for a class, then an empty one with no parameters is automatically provided.

You seemed to think that inheritance works differently in C# than Java, but in this case Java behaves the same way. See Section 8.8 in the Java spec.

Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding.

For more information on possible reasoning behind this decision, see this StackOverflow question.




回答2:


You should write constructor in DienstGruppe to inherit it from base class like this:

public DienstGruppe(String line) : base(line) { }

So it requires constructor in child class.



来源:https://stackoverflow.com/questions/12113131/c-sharp-activator-createinstance-for-extending-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!