C# Activator createInstance 用于扩展类

标签 c# inheritance activator extending createinstance

我有一个基类,如下所示:

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);
    }

我还有一个扩展这个类的子类。

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

然后我尝试使用 Activator.CreateInstance() 函数创建一个对象,如下所示:

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

注意:this.GetType() 由扩展类在 Data 函数中使用,以获取当前类的类型。

但这会导致一个问题。奇怪的是我收到一个错误,该类(在我的例子中是 DienstGruppe)没有构造函数。我想 C# 中的继承与 Java 中的继承不同。那么我该如何解决这个问题呢?

虽然它适用于“数据”。

问候,多米尼克

最佳答案

除了 Pavel 的回答(关于在子类中要求具有适当签名的构造函数是正确的)之外,可能值得指出您为什么需要这样做。

根据 C# 语言规范的第 1.6.7.1 节,在 C# 中,构造函数不是继承的。

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.

您似乎认为继承在 C# 中的工作方式与 Java 不同,但在这种情况下,Java 的行为方式相同。请参阅 Java 规范中的 第 8.8 节

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

有关此决定背后的可能原因的更多信息,请参阅 this StackOverflow question.

关于C# Activator createInstance 用于扩展类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12113131/

相关文章:

c# - 如何声明一个以元组列表作为参数的 f# 方法?

c# - 尽管通过代码运行测试,ReSharper dotcover 仍显示 0% 的覆盖率

c# - 有人熟悉 Winforms 的 "sticky windows"库吗?

c# - 反序列化到自定义列表

C++在向继承树的某些类引入附加接口(interface)时避免代码重复

PHP 继承和 MySQL

c# - 使用 Activator 创建实例

c# - 使用 IN 子句更新 SQL Server 中的多行