代码之家  ›  专栏  ›  技术社区  ›  John Mills

如何使用类型调用默认值(T)?[复制品]

  •  5
  • John Mills  · 技术社区  · 14 年前

    这个问题已经有了答案:

    在C我可以使用 default(T) 获取类型的默认值。我需要在运行时从 System.Type . 我该怎么做?

    例如沿着这条线的东西(不起作用)

    var type = typeof(int);
    var defaultValue = default(type);
    
    3 回复  |  直到 9 年前
        1
  •  9
  •   Julien Hoarau    14 年前

    null Activator.CreateInstance

    public static object Default(Type type)
    {
       if(type.IsValueType)
       {
          return Activator.CreateInstance(type);
       }
    
       return null;
    }
    
        2
  •  6
  •   Jon Skeet    9 年前

    Expression.Default

    Expression expression = Expression.Default(type);
    

    object defaultValue = Array.CreateInstance(type, 1).GetValue(0);
    

    void

        3
  •  3
  •   Thomas Levesque    14 年前

    • Activator.CreateInstance

      public static object GetDefaultValue(Type type)
      {
          if (type.IsValueType)
          {
              return Activator.CreateInstance(type);
          }
          else
          {
              return null;
          }
      }
      

    FormatterServices.GetUninitializedObject