【问题标题】:How do I determine the underlying type of an array [duplicate]如何确定数组的基础类型 [重复]
【发布时间】:2012-07-06 00:26:18
【问题描述】:
可能重复:
How do I get the Array Item Type from Array Type in .net
如果我有一个特定类型的数组,有没有办法知道该类型到底是什么?
var arr = new []{ "string1", "string2" };
var t = arr.GetType();
t.IsArray //Evaluates to true
//How do I determine it's an array of strings?
t.ArrayType == typeof(string) //obviously doesn't work
【问题讨论】:
标签:
c#
.net
arrays
reflection
【解决方案1】:
Type.GetElementType - 在派生类中重写时,返回当前数组、指针或引用类型包含或引用的对象的类型。
var arr = new []{ "string1", "string2" };
Type type = array.GetType().GetElementType();
【解决方案2】:
由于您的类型在编译时是已知的,因此您只需以 C++ 方式进行检查。像这样:
using System;
public class Test
{
public static void Main()
{
var a = new[] { "s" };
var b = new[] { 1 };
Console.WriteLine(IsStringArray(a));
Console.WriteLine(IsStringArray(b));
}
static bool IsStringArray<T>(T[] t)
{
return typeof(T) == typeof(string);
}
}
(产生True,False)