创建类型的默认实例
什么是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? }
对于任何引用类型,默认值为null实例。 对于任何值类型,可以通过Activator.CreateInstance
获取默认值。 但是当你有一个名为instance
的变量时,它建议你想要一个实际的实例而不是一个null引用…所以你可以这样做:
public object GetDefaultValue(Type type) { return type.IsValueType ? Activator.CreateInstance(type) : null; }
……这不是很清楚它有多有用。 这是类型的默认值 ,与默认的类型实例不同。