我知道C#支持数组协变,就像这样:
object[] array = new string[3];
但是当它尝试编译以下代码时,我遇到了一个错误。
class Dummy<K,T> where T:K
{
public void foo()
{
K[] arr = new T[4];
}
}
它说“无法将类型'T[]'隐式转换为'K[]'”
我为什么会得到这个错误?
我知道C#支持数组协变,就像这样:
object[] array = new string[3];
class Dummy<K,T> where T:K
{
public void foo()
{
K[] arr = new T[4];
}
}
它说“无法将类型'T[]'隐式转换为'K[]'”
我为什么会得到这个错误?
class Dummy<K,T> where T : class, K
它可以正常工作。您不必指定K是引用类型,因为如果T是引用类型并且派生自或实现了K,则K也必须是引用类型。(至少我认为是这样的推理。为了清晰起见,也可以添加where K : class
)。
类型 T 必须支持隐式转换为 K。例如:
T a = new T(); K b = a;
必须是有效的。