【问题标题】:Given simple type T, get array type T[] [duplicate]给定简单类型 T,得到数组类型 T[] [重复]
【发布时间】:2013-04-25 10:00:58
【问题描述】:

在给定T 的情况下,如何获取Array of type T 的类型?

下面是 LinqPad 友好的 sn-p:

void Main()
{
    Type t = typeof(string);
    Type tArray = GetArrayType(t);
    tArray.Dump(); // System.String[]
}
Type GetArrayType(Type t)
{
    ////this is cheating !!
    //return typeof(string[]); 
}

【问题讨论】:

    标签: .net arrays reflection types


    【解决方案1】:

    这样就可以了:

    type.MakeArrayType()
    

    例如:

    int a = 123;
    Type aType = a.GetType();
    Type aArrayType = aType.MakeArrayType();
    
    // aArrayType.FullName = "System.Int32[]"
    

    【讨论】:

      【解决方案2】:

      更新

      知道a better way :)

      Type GetArrayType(Type t){
          return t.MakeArrayType();
      }
      

      原答案:

      这行得通,但我希望能少一些 hacky

      Type GetArrayType(Type t){
          return Type.GetType(t + "[]");
      }
      

      【讨论】:

      • 这就是我要做的......
      猜你喜欢
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-08-19
      • 2017-12-29
      • 2019-01-31
      • 2019-11-17
      • 2020-10-28
      相关资源
      最近更新 更多