簡體   English   中英

如何區分類型:Int32 []和Int32 [*]?

[英]How to differentiate the types: Int32[] & Int32[*]?

給出以下代碼:

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

如果值類型已知:

var t1 = type1 == typeof(int[]); // true
var t2 = type2 == typeof(int[]); // false

參考如何檢查對象是否是某種類型的數組?


其他可能有用的差異:

var tt1 = type1.GetConstructors().Length; // 1
var tt2 = type2.GetConstructors().Length; // 2

var ttt1 = type1.GetMembers().Length; // 47
var ttt2 = type2.GetMembers().Length; // 48

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM