c# - 如何使用泛型类型的子类初始化泛型属性?

标签 c# generics inheritance initialization

我想用其中一个子类填充通用属性。但是我得到这个错误:

Cannot implicitly convert type 'Child1' to 'T'

我该怎么做?

例如:

考虑这些父类和子类:

public abstract class Parent
{
    public int P1 { get; set; }

    public abstract int DoSomething();
}
public class Child1 : Parent
{
    public override int DoSomething() { return P1 * 2; }
}
public class Child2 : Parent
{
    public override int DoSomething() { return P1 * 3; }
}

还要考虑这个示例泛型类:

public class Sample<T> where T: Parent
{
    T ChildObject { get; set; }

    public int Test()
    {
        ChildObject = new Child1 { P1 = 2 }; // Error: Cannot implicitly convert type 'Child1' to 'T'

        return ChildObject.DoSomething();
    }
}

更多解释:

我的错误是我试图初始化通用类中的子类。按照接受的答案,我应该只添加 new constraint 并执行 ChildObject = new T { P1 = 2 }; 然后使用 ChildObject.DoSomething();


解决方案:

public class Sample<T> where T: Parent, new()
{
    T ChildObject { get; set; }

    public int Test()
    {
        ChildObject = new T { P1 = 2 }; // Fixed :)

        return ChildObject.DoSomething();
    }
}

最佳答案

将您的 Sample 类更改为:

public class Sample<T> where T : Parent, new()
{
    T ChildObject { set; get; }
    public Sample()
    {
        ChildObject = new T(); 
    }
}

您现在可以创建一个实例:

var sample = new Sample<Child2>();

为了让它工作,Child1Child2 需要有一个公共(public)的无参数构造函数。这记录在案 here

关于c# - 如何使用泛型类型的子类初始化泛型属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52179815/

相关文章:

c# - DataGridColumn 与动态生成的数据绑定(bind)

c# datagridview 行宽在滚动时自动增加

java - 有没有办法减少多个类型参数?

swift - 在 Swift 中创建通用 Realm 存储库

grails - 使用泛型在Groovy中传递类的实例

.net - 在整个asp.net MVC 4项目中使用基本 Controller

c++ - 需要类语法解释

c# - 在 MEF 2 中使用封闭类型组合开放通用类型

c# - EntityFramework 代码优先继承,在派生类上具有急切的包含关系

c# - 复制多维数组的一部分