【问题标题】:Create default instance of type [duplicate]创建类型的默认实例[重复]
【发布时间】:2012-05-08 05:54:31
【问题描述】:

什么是反射等价物:

default(object);  //null

当我直到运行时才知道类型时,例如

public void Method(Type type)
{
   var instance = type.CreateDefault(); //no such method exists, but I expect there is a way of doing this?
} 

【问题讨论】:

    标签: c# .net reflection


    【解决方案1】:

    对于任何引用类型,默认值为空实例。对于任何值类型,可以通过Activator.CreateInstance获取默认值。但是当你有一个名为 instance 的变量表明你想要一个 实际实例 而不是空引用时......所以当你 可以 这样做时:

    public object GetDefaultValue(Type type)
    {
        return type.IsValueType ? Activator.CreateInstance(type) : null;
    } 
    

    ...目前还不清楚这有多大用处。是该类型的默认value,与该类型的默认instance不同。

    【讨论】:

    • 不,在这种情况下我对 null 很满意。所以我将使用 Activator 作为值类型,否则为 null。谢谢乔恩。
    猜你喜欢
    • 2016-05-12
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 2017-03-09
    相关资源
    最近更新 更多