如何确定数组的基础类型

时间:2012-07-05 15:00:20

标签: c# .net arrays reflection

  

可能重复:
  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

2 个答案:

答案 0 :(得分:3)

Type.GetElementType - 在派生类中重写时,返回当前数组,指针或引用类型所包含或引用的对象的类型。

var arr = new []{ "string1", "string2" };
Type type = array.GetType().GetElementType(); 

答案 1 :(得分: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);
    }
}

(生成TrueFalse