创建类型的默认实例

时间:2012-04-27 13:19:34

标签: c# .net reflection

反射等价物是什么:

default(object);  //null

当我在运行时之前没有这种类型时,例如

public void Method(Type type)
{
   var instance = type.CreateDefault(); //no such method exists, but I expect there is a way of doing this?
} 

1 个答案:

答案 0 :(得分:13)

对于任何引用类型,默认值为null实例。对于任何值类型,可以通过Activator.CreateInstance获取默认值。但是当你有一个名为instance的变量时,它建议你想要一个实际实例而不是一个空引用...所以当你可以这样做时:

public object GetDefaultValue(Type type)
{
    return type.IsValueType ? Activator.CreateInstance(type) : null;
} 

......现在还不是很清楚这是多么有用。这是该类型的默认,与该类型的默认实例不同。