Nés*_* A. 26 .net c# types runtime
可能重复:
类型的默认值
在C#中,要获取Type的默认值,我可以写...
var DefaultValue = default(bool);`
Run Code Online (Sandbox Code Playgroud)
但是,如何为提供的Type变量获取相同的默认值?
public object GetDefaultValue(Type ObjectType)
{
return Type.GetDefaultValue(); // This is what I need
}
Run Code Online (Sandbox Code Playgroud)
或者,换句话说,"默认"关键字的实现是什么?
mic*_*er1 42
我认为Frederik的功能实际上应该是这样的:
public object GetDefaultValue(Type t)
{
if (t.IsValueType)
{
return Activator.CreateInstance(t);
}
else
{
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
Mar*_*ell 15
您也应该排除这种Nullable<T>情况,以减少几个CPU周期:
public object GetDefaultValue(Type t) {
if (t.IsValueType && Nullable.GetUnderlyingType(t) == null) {
return Activator.CreateInstance(t);
} else {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14084 次 |
| 最近记录: |