简体   繁体   English

C#无法将类型'T'隐式转换为'object [*,*]'

[英]C# Cannot implicitly convert type 'T' to 'object[*,*]'

I have a method that I'm attempting to update to accept multiple types of data so I used a generic. 我有一种方法正在尝试更新以接受多种类型的数据,因此我使用了通用方法。 I got it working with a couple different types, but one type that is being passed in is object[,] . 我使用了几种不同的类型,但是传入的一种类型是object[,] When I try to set the data to that type, I get the following error on conversion: 当我尝试将数据设置为该类型时,在转换时出现以下错误:

Cannot implicitly convert type 'T' to 'object[*,*]'

The code is pretty simple with: 该代码非常简单:

object[,] data = (T)(object[,])element;

Any ideas? 有任何想法吗?

The issue you're seeing is that since T neither derives from object[,] nor implements an explicit conversion , the code has literally no idea how to perform the conversion. 您看到的问题是,由于T既不是从object[,]派生的object[,]也不是实现显式的 转换 ,因此代码实际上不知道如何执行转换。 This is because under the hood, conversions either box or unbox derived types, or call the conversion method in order to return the desired output type. 这是因为在幕后,转换是box或unbox派生类型,或调用转换方法以返回所需的输出类型。

Since you're using a Generic, you can constrain the type using a where statement. 由于使用的是泛型,因此可以使用where语句约束类型。 As long as the constrained type (or a more derived type) defines and explicit conversion to (or derives from) object[,] , you'll be able to perform the conversion. 只要受约束的类型(或更多派生的类型)定义并显式转换为object[,] (或从中派生),您就可以执行转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM