简体   繁体   English

我可以将一个实现接口的通用 T 数组转换为这个特定的接口数组吗?

[英]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 and T differ only in element type. ST仅在元素类型上有所不同。 In other words, S and T have the same number of dimensions.换句话说, ST具有相同的维数。
  • Both SE and TE are reference_types. SETE都是 reference_types。
  • An implicit reference conversion exists from SE to TE .SETE存在隐式引用转换。

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.

相关问题 为什么我不能将一个项目转换为泛型类型——其中泛型类型是一个接口,并且在检查该项目是否实现了所述接口之后? - Why can't I cast an item to a generic type — where the generic type is an interface, and after checking that the item implements said interface? 如何将通过接口标识的对象转换为实现该接口的泛型类的特定对象 - How to cast an object identified via an interface to the specific object of a Generic class that implements that interface 通过搜索特定的泛型接口参数获取实现泛型接口的类型 - Get type that implements generic interface by searching for a specific generic interface parameter 泛型接口转换为特定接口 - generic type interface cast to a specific interface 检查对象是否实现特定的通用接口 - Check if object implements specific generic interface 在C#中,如何判断泛型T是否是(不是实现!)接口? - In C#, how can I tell whether a generic type, T, is (not implements!) an interface? T实现接口的通用方法<T> - Generic method where T implements Interface<T> foreach循环无法将类型转换为它实现的接口 - foreach loop can not cast type to the interface it implements 通用方法,其中 T 是实现接口的列表 - Generic Method where T is List that implements interface 可以转换为接口,但不能转换为泛型 - Can cast to interface, but not to generic type
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM