我怎样才能调用默认(T)与类型?类型

2023-09-02 12:00:23 作者:孟婆、来杯优乐美

在C#中,我可以使用默认(T)来获得一个类型的默认值。我需要从的System.Type 获取默认的类型在运行时。我怎样才能做到这一点?

例如。沿着这行的东西(这不工作)

  VAR类型= ty​​peof运算(INT);
VAR设置defaultValue =默认值(类型);
 

解决方案 JavaScript数据类型 原始类型与引用类型 object 详谈 javascript weixin 34162401的博客 CSDN博客

有关引用类型返回,一个值类型,你可以尝试使用 Activator.CreateInstance 或调用类型的默认构造函数。

 公共静态对象的默认值(类型类型)
{
   如果(type.IsValueType)
   {
      返回Activator.CreateInstance(类型);
   }

   返回null;
}
 

In c# I can use default(T) to get the default value of a type. I need to get the default type at run time from a System.Type. How can I do this?

E.g. Something along the lines of this (which doesn't work)

var type = typeof(int);
var defaultValue = default(type);

解决方案

For a reference type return null, for a value type, you could try using Activator.CreateInstance or calling the default constructor of the type.

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

   return null;
}