开发者

In .NET, at runtime: How to get the default value of a type from a Type object? [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Default value of a type

In C#, to get the default value of a Type, i can write...

var DefaultValue = default(bool);`

But, how to get the same default value for a supplied Type variable?.

public object GetDefaultValue(Type ObjectType)
{
    return Type.GetDe开发者_JAVA百科faultValue();  // This is what I need
}

Or, in other words, what is the implementation of the "default" keyword?


I think that Frederik's function should in fact look like this:

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


You should probably exclude the Nullable<T> case too, to reduce a few CPU cycles:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜