在.NET中,在运行时:如何从Type对象获取类型的默认值?
可能重复:
类型的默认值
在C#中,要获取Type的默认值,我可以写…
var DefaultValue = default(bool);`
但是,如何为提供的Type变量获取相同的默认值?
public object GetDefaultValue(Type ObjectType) { return Type.GetDefaultValue(); // This is what I need }
或者,换句话说,“默认”关键字的实现是什么?
我认为Frederik的function实际上应该是这样的:
public object GetDefaultValue(Type t) { if (t.IsValueType) { return Activator.CreateInstance(t); } else { return null; } }
您也应该排除Nullable
情况,以减少几个CPU周期:
public object GetDefaultValue(Type t) { if (t.IsValueType && Nullable.GetUnderlyingType(t) == null) { return Activator.CreateInstance(t); } else { return null; } }