在.NET中,在运行时:如何从Type对象获取类型的默认值? [重复]

时间:2021-01-04 16:05:35

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 情况,以减少几个CPU周期:

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 情况,以减少几个CPU周期:

public object GetDefaultValue(Type t) {
    if (t.IsValueType && Nullable.GetUnderlyingType(t) == null) {
        return Activator.CreateInstance(t);
    } else {
        return null;
    }
}