我可以将实现接口的 T 的通用数组转换为这个特定的接口数组吗?
Can I cast a generic array of T that implements an interface, to this specific interface array?
我想做这样的事情:自动将 T 的数组转换为 T 实现的某个接口:
public static void GenericFunction<T>(T[,] genericArray) where T : ISomeInterface
{
OtherFunction(genericArray);
}
public static void OtherFunction(ISomeInterface[,] interfaceArray)
{
//stuff
}
这会产生错误“无法从 'T[,]' 转换为 'ISomeInterface[,]'”
这是否可以在不使用 Select 或迭代整个数组的情况下完成?
从元素类型为SE
的数组类型S
隐式转换为元素类型为TE
的数组类型T
的必要条件是( language spec):
S
and T
differ only in element type. In other words, S
and T
have the same number of dimensions.
- Both
SE
and TE
are reference_types.
- An implicit reference conversion exists from
SE
to TE
.
在你的情况下,不能保证 T
是引用类型(第二个条件)。因此,使代码工作的一种方法是将 T
限制为引用类型:
public static void GenericFunction<T>(T[,] genericArray) where T : class, ISomeInterface
我想做这样的事情:自动将 T 的数组转换为 T 实现的某个接口:
public static void GenericFunction<T>(T[,] genericArray) where T : ISomeInterface
{
OtherFunction(genericArray);
}
public static void OtherFunction(ISomeInterface[,] interfaceArray)
{
//stuff
}
这会产生错误“无法从 'T[,]' 转换为 'ISomeInterface[,]'” 这是否可以在不使用 Select 或迭代整个数组的情况下完成?
从元素类型为SE
的数组类型S
隐式转换为元素类型为TE
的数组类型T
的必要条件是( language spec):
S
andT
differ only in element type. In other words,S
andT
have the same number of dimensions.- Both
SE
andTE
are reference_types.- An implicit reference conversion exists from
SE
toTE
.
在你的情况下,不能保证 T
是引用类型(第二个条件)。因此,使代码工作的一种方法是将 T
限制为引用类型:
public static void GenericFunction<T>(T[,] genericArray) where T : class, ISomeInterface