Possible Duplicate:
Default value of a type可能重复:类型的默认值
In C#, to get the default value of a Type, i can write...
在C#中,要获取Type的默认值,我可以写...
var DefaultValue = default(bool);`
But, how to get the same default value for a supplied Type variable?.
但是,如何为提供的Type变量获取相同的默认值?
public object GetDefaultValue(Type ObjectType)
{
return Type.GetDefaultValue(); // This is what I need
}
Or, in other words, what is the implementation of the "default" keyword?
或者,换句话说,“默认”关键字的实现是什么?
2 个解决方案
#1
36
I think that Frederik's function should in fact look like this:
我认为Frederik的功能实际上应该是这样的:
public object GetDefaultValue(Type t)
{
if (t.IsValueType)
{
return Activator.CreateInstance(t);
}
else
{
return null;
}
}
#2
13
You should probably exclude the Nullable<T>
case too, to reduce a few CPU cycles:
您也应该排除Nullable
public object GetDefaultValue(Type t) {
if (t.IsValueType && Nullable.GetUnderlyingType(t) == null) {
return Activator.CreateInstance(t);
} else {
return null;
}
}
#1
36
I think that Frederik's function should in fact look like this:
我认为Frederik的功能实际上应该是这样的:
public object GetDefaultValue(Type t)
{
if (t.IsValueType)
{
return Activator.CreateInstance(t);
}
else
{
return null;
}
}
#2
13
You should probably exclude the Nullable<T>
case too, to reduce a few CPU cycles:
您也应该排除Nullable
public object GetDefaultValue(Type t) {
if (t.IsValueType && Nullable.GetUnderlyingType(t) == null) {
return Activator.CreateInstance(t);
} else {
return null;
}
}