首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何区分类型: Int32[]和Int32[*]?

如何区分类型: Int32[]和Int32[*]?
EN

Stack Overflow用户
提问于 2017-03-26 07:41:05
回答 2查看 193关注 0票数 4

给定以下代码:

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

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

最好不使用任何繁琐的解决方案(例如实例化类型或在名称中查找"*“)。

上下文:我正在构建一个序列化程序,我需要它对存在的每个类型都有效,所以像== typeof(int[])这样的常量比较将不起作用。

EN

回答 2

Stack Overflow用户

发布于 2017-03-26 09:18:59

检查类型是否未通过比较是一个有效的选项,但是,如果要检查类型的特定属性,例如要知道将其强制转换为哪种类型的数组,则可以使用Type.GetElementType()来检查并确认数组中的元素是相同类型的。以下代码可能会对您的投资有所帮助:

代码语言:javascript
复制
// 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 :)

调试控制台输出:

代码语言:javascript
复制
type1: System.Int32[]
type1: IsArray=True; ElementType=System.Int32; Is Int32[]: True
type2: System.Int32[*]
type2: IsArray=True; ElementType=System.Int32; Is Int32[]: False
票数 2
EN

Stack Overflow用户

发布于 2017-03-26 08:57:35

如果值类型已知:

代码语言:javascript
复制
var t1 = type1 == typeof(int[]); // true
var t2 = type2 == typeof(int[]); // false

参考How to check if object is an array of a certain type?

其他可能有用的差异:

代码语言:javascript
复制
var tt1 = type1.GetConstructors().Length; // 1
var tt2 = type2.GetConstructors().Length; // 2

var ttt1 = type1.GetMembers().Length; // 47
var ttt2 = type2.GetMembers().Length; // 48
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43023238

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档