[英]Can I cast a generic array of T that implements an interface, to this specific interface array?
I would like to do something like this: automatically convert array of T to some interface that T implements:我想做这样的事情:自动将 T 数组转换为 T 实现的某个接口:
public static void GenericFunction<T>(T[,] genericArray) where T : ISomeInterface
{
OtherFunction(genericArray);
}
public static void OtherFunction(ISomeInterface[,] interfaceArray)
{
//stuff
}
This produces an error "cannot convert from 'T[ , ]' to 'ISomeInterface[ , ]' " Is this possible to do without using Select or iterating whole array?这会产生错误“无法从 'T[ , ]' 转换为 'ISomeInterface[ , ]' ”这是否可以在不使用 Select 或迭代整个数组的情况下完成?
The necessary conditions for an implicit conversion from an array type S
with element type SE
to another array type T
with element type TE
to exist are ( language spec ):存在从元素类型为
SE
的数组类型S
到元素类型为TE
的另一个数组类型T
的隐式转换的必要条件是( 语言规范):
S
andT
differ only in element type.S
和T
仅在元素类型上有所不同。 In other words,S
andT
have the same number of dimensions.换句话说,
S
和T
具有相同的维数。- Both
SE
andTE
are reference_types.SE
和TE
都是 reference_types。- An implicit reference conversion exists from
SE
toTE
.从
SE
到TE
存在隐式引用转换。
In your case, there is no guarantee that T
is a reference type (second condition).在您的情况下,不能保证
T
是引用类型(第二个条件)。 One way to make your code work is therefore to constrain T
to reference types:因此,使您的代码工作的一种方法是将
T
限制为引用类型:
public static void GenericFunction<T>(T[,] genericArray) where T : class, ISomeInterface
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.