c# - 如何区分类型 : Int32[] & Int32[*]?

标签 c# reflection types

给定以下代码:

var type1 = typeof(int[]); // Int32[]
var type2 = Array.CreateInstance(elementType: typeof(int),
                                 lengths: new [] {0},
                                 lowerBounds: new []{1}).GetType(); // Int32[*]

给定一个数组类型(.IsArray 返回 true 的类型),我如何可靠地区分这两种数组类型?

最好不要使用任何 hacky 解决方案(比如实例化类型或在名称中查找“*”)。

上下文:我正在构建一个序列化程序,我需要它适用于所有存在的类型,因此像 == typeof(int[]) 这样的持续比较将不起作用。

最佳答案

检查类型是否失败比较是一个有效的选项,但是如果你想检查一个类型的特定属性,例如知道要将它转换成什么类型​​的数组,你可以使用 Type.GetElementType() 来检查并确认数组中的元素属于同一类型。以下代码可能有助于您的调查:

// Initialise our variables
object list1 = new int[5]; // Int32[]
object list2 = Array.CreateInstance(elementType: typeof(int),
                                    lengths: new[] { 0 },
                                    lowerBounds: new[] { 1 });
var type1 = list1.GetType();
var type2 = list2.GetType();

Debug.WriteLine("type1: " + type1.FullName);
Debug.WriteLine($"type1: IsArray={type1.IsArray}; ElementType={type1.GetElementType().FullName}; Is Int32[]: {type1 == typeof(Int32[])}");
Debug.WriteLine("type2: " + type2.FullName);
Debug.WriteLine($"type2: IsArray={type2.IsArray}; ElementType={type2.GetElementType().FullName}; Is Int32[]: {type2 == typeof(Int32[])}");

// To make this useful, lets join the elements from the two lists
List<Int32> outputList = new List<int>();
outputList.AddRange(list1 as int[]);
if (type2.IsArray && type2.GetElementType() == typeof(Int32))
{
    // list2 can be safely be cast to an Array because type2.IsArray == true
    Array arrayTemp = list2 as Array;
    // arrayTemp can be cast to IEnumerable<Int32> because type2.GetElementType() is Int32.
    // We have also skipped a step and cast ToArray
    Int32[] typedList = arrayTemp.Cast<Int32>().ToArray();
    outputList.AddRange(typedList);
}

// TODO: do something with these elements in the output list :)

调试控制台输出:

type1: System.Int32[]
type1: IsArray=True; ElementType=System.Int32; Is Int32[]: True
type2: System.Int32[*]
type2: IsArray=True; ElementType=System.Int32; Is Int32[]: False

关于c# - 如何区分类型 : Int32[] & Int32[*]?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43023238/

相关文章:

c# - 为什么在内部类上 C# 动态找不到接口(interface)的方法?

c# - 模型将集合属性与局部 View 绑定(bind)

c# - 使用 C# 将多个值传递给 SQL 内联查询中的单个参数

java - 使用反射时如何检查字段是否有注释

c# - 在 C# 中按类名作为字符串获取类属性

生日的 C# 数据类型

c# - ASP.NET 配置文件保存被旧值覆盖

c# - 已尝试附加或添加不是新实体,可能是从另一个 DataContext 加载的

python - 在 python 中查找类型 - TypeError 'unicode' 对象不可调用

types - 如何在结构上定义可变字段?去