我有一个通用参数 T,在一个特定情况下它是一个数组。是否可以将对象数组转换为 typeof(T).GetElementType() 的数组?例如:
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>并得到一个运行时异常,糟糕!
但是,为什么一开始就限制为一个数组呢?只需让泛型参数成为元素本身的类型即可:
public TResult[] Execute<TResult>()
{
var myArray = ...
return myArray.Cast<TResult>().ToArray();
}
更新:回应您的评论:
如果Execute是一个你不能改变的接口(interface)方法,那么你可以这样做:
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;
}
