C#将数组转换为元素类型

C#将数组转换为元素类型

问题描述:

我有一个通用参数T,在一个特殊情况下它是一个数组。是否可以将对象数组转换为 typeof(T).GetElementType()的数组?例如:

I have a generic argument T which is an array in one particular case. Is it possible to cast array of objects to the array of typeof(T).GetElementType()? For example:

public TResult Execute<TResult>()// MyClass[] in this particular case
{
    var myArray = new List<object>() { ... }; //actual type of those objects is MyClass
    Type entityType = typeof(TResult).GetElementType(); //MyClass
    //casting to myArray to array of entityType 
    TResult result = ...;
    return result;    
} 


这不是一个好主意。您无法将 TResult 约束为数组,因此使用您当前的代码,有人可以调用 Excute< int> 并获得运行时异常,y!

This is not a good idea. You have no way to constrain TResult to an array, so with your current code, someone could call Excute<int> and get a runtime exception, yuck!

但是,为什么要限制到数组开头呢?只需让通用参数成为元素本身的类型即可:

But, why constrain to an array to begin with? Just let the generic parameter be the type of the element itself:

public TResult[] Execute<TResult>()
{
    var myArray = ... 
    return myArray.Cast<TResult>().ToArray();
}

更新:针对您的评论:

如果 Execute 是无法更改的接口方法,则可以执行以下操作:

If Execute is an interface method you can not change, then you can do the following:

public static TResult Execute<TResult>()
{
    var myArray = new List<object>() { ... };
    var entityType = typeof(TResult).GetElementType();
    var outputArray = Array.CreateInstance(entityType, myArray.Count);
    Array.Copy(myArray.ToArray(), outputArray, myArray.Count); //note, this will only work with reference conversions. If user defined cast operators are involved, this method will fail.
    return (TResult)(object)outputArray;
}