2009-02-06 69 views
4

我知道“default”关键字返回静态确定类型的默认值,例如this question如何以非泛型方式获取某个类型的默认值?

但是,给定一个类型的实例,是否有一种简单的方法来动态获取此类型的默认值? 我发现谷歌搜索,而唯一的办法就是this

static object DefaultValue(Type myType) 
{ 
    if (!myType.IsValueType) 
     return null; 
    else 
     return Activator.CreateInstance(myType); 
} 

,但我想如果可能的话,避免Activator类。

+0

欢迎世界表达? http://stackoverflow.com/questions/6582259/fast-creation-of-objects-instead-of-activator-createinstancetype :) – nawfal 2013-04-24 12:05:44

回答

6

这可能是您的最佳路线。

我不会害怕在这里使用Activator类。这是编译器所依赖的一个非常标准的类。比如这个VB代码

Public Sub Example(Of T as New)() 
    Dim x = new T() 
End Sub 

转换成大致是这样的代码

Public Sub Example(Of T As New)() 
    Dim x = Activator.CreateInstance(OF T) 
ENd Sub 
+0

这是泛型(OP想要避免),并不是相同的“默认“ - 它应该为类返回null。 – 2009-02-06 13:40:48

6

你为什么要避免激活?基本上这样做的方式。

我的意思是,你可以写一个通用的方法,然后通过反射调用,但这是一个相当可怕的“长切”,只是为了避免Activator。