我有一个通用参数 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;
}
关于C# 将数组转换为元素类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39095682/