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

标签 c# arrays generics casting

我有一个通用参数 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/

相关文章:

c# - Asp.Net 单例模式场景

java - 即使 CSV 行中没有值,OpenCSV 也会返回一个字符串

c - 返回指向子数组的指针

c# - 星搜索算法

c# - 如何在 C# 中获取 IPv6 地址?

javascript - 将 @Html.EditorFor "Date"值传回 Controller ,操作值并传回 View 以填充下拉列表

Ruby 二维数组到具有来自不同数组的键的哈希数组

c# - 使用通用类型进行转换

generics - 从通用集合中选择类型的子集

typescript - Typescript 通用参数的模式有时可能是未定义的?