我想用其中一个子类填充通用属性。但是我得到这个错误:
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>();
为了让它工作,Child1
和 Child2
需要有一个公共(public)的无参数构造函数。这记录在案 here
关于c# - 如何使用泛型类型的子类初始化泛型属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52179815/