在.NET中,在运行时:如何从一个类型的对象类型的默认值? [英] In .NET, at runtime: How to get the default value of a type from a Type object?
本文介绍了在.NET中,在运行时:如何从一个类型的对象类型的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
可能重复:
一类的默认值
Possible Duplicate:
Default value of a type
在C#中,得到一个类型的默认值,我可以写...
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?
推荐答案
我认为弗雷德里克的作用其实应该是这样的:
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;
}
}
这篇关于在.NET中,在运行时:如何从一个类型的对象类型的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文