在C#中,我可以使用默认(T)
来获得一个类型的默认值。我需要从的System.Type
获取默认的类型在运行时。我怎样才能做到这一点?
例如。沿着这行的东西(这不工作)
VAR类型= typeof运算(INT);
VAR设置defaultValue =默认值(类型);
解决方案
有关引用类型返回空
,一个值类型,你可以尝试使用 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;
}