[英]How do you get the Element Type of an Empty Array in C#?
Int32[] myArray = new Int32[0];
//Somewhere else in code:
Type t = myArray.GetType();
//t == Int32[]
//element type of t == ???
How do I find out the element type that t was created to store. 我如何找出创建要存储的元素类型。
The only example I've found works on arrays that aren't empty, where you simply do myArray[i].GetType(). 我发现的唯一示例适用于不为空的数组,您只需在其中执行myArray [i] .GetType()。 So what do you do for array length 0?
那么,对于数组长度为0的情况,您该怎么做?
FYI: I did the following and it works fine, but wow... it uses string conversion and is super ugly. 仅供参考:我做了以下工作,但效果很好,但是,哇...它使用字符串转换,而且非常丑陋。 There's got to be a better way:
必须有一个更好的方法:
Type t = myArray.GetType();
string strT = t.ToString();
string strArrayBase = strT.Substring(0, strT.Length - 2);
Type elementType = Type.GetType(strArrayBase);
You can use .GetElementType()
您可以使用
.GetElementType()
Eg: 例如:
> int[] arr = new int[0];
> arr.GetType().GetElementType()
[System.Int32]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.