运行时类型的默认值 [英] Default value of a type at Runtime
问题描述
对于任何给定的类型,我想知道其默认值。
For any given type i want to know its default value.
在C#中,有一个名为default的关键字,用于执行此操作
In C#, there is a keyword called default for doing this like
object obj = default(Decimal);
但是我有一个Type实例(称为myType),如果我这样说,
but I have an instance of Type (called myType) and if I say this,
object obj = default(myType);
不起作用
是有什么好的方法吗?
我知道一个巨大的开关块将起作用,但这不是一个好选择。
Is there any good way of doing this? I know that a huge switch block will work but thats not a good choice.
推荐答案
实际上只有两种可能: null
用于引用类型, new myType()
用于值类型(对于int,float等,其对应值为0 )因此,您实际上只需要考虑以下两种情况:
There's really only two possibilities: null
for reference types and new myType()
for value types (which corresponds to 0 for int, float, etc) So you really only need to account for two cases:
object GetDefaultValue(Type t)
{
if (t.IsValueType)
return Activator.CreateInstance(t);
return null;
}
(由于值类型始终具有默认构造函数,因此调用Activator.CreateInstance永远不会失败)。
(Because value types always have a default constructor, that call to Activator.CreateInstance will never fail).
这篇关于运行时类型的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!