我想实例化泛型类型的实例并传递它们,就好像它们是它们实现的接口(interface)的泛型对象一样,如下所示。显然,这是不允许的。这是为什么?处理这种情况的一般做法是什么?谢谢。
public class MyType<T> where T : IComparable { }
MyType<IComparable> things = new MyType<Int32>();
这会出现错误:
Cannot implicitly convert type MyType<Int32> to MyType<IComparable>
我想这样做是因为我需要不同类型的 things
我想传递给更通用的方法,例如
public void DoSomething(MyType<IComparable> things) {...}
最佳答案
泛型类型参数的赋值兼容性不会使泛型类型本身的赋值兼容。这就是原因:假设我们像这样声明了泛型类:
public class MyType<T> where T : IComparable
{
public T Value { get; set; }
}
我们假设这可以编译...
var intObject = new MyType<int> { Value = 42 };
MyType<IComparable> things = intObject; // Does not compile!
...然后我们可以写
// things.Value has the static type IComparable
things.Value = "hello"; // Allowed because string is IComparable
但是这是不可能的,因为底层对象是 MyType<int>
因此它的Value
属性的类型为 int
。因此,我们不允许替换 MyType<int>
对于MyType<IComparable>
.
关于c# - 将更具体的泛型类型分配给不太具体的类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75346167/