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

北城余情 提交于 2019-12-04 15:18:44

问题


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.GetDefaultValue();  // This is what I need
}

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


回答1:


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;
    }
}



回答2:


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;
    }
}


来源:https://stackoverflow.com/questions/2686678/in-net-at-runtime-how-to-get-the-default-value-of-a-type-from-a-type-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!