创建类型的默认实例 [英] Create default instance of type
问题描述
什么是反射等效的:
默认(对象); //空值
在我没有的类型,直到运行时,如:
公共无效方法(Type类型)
{
VAR实例= type.CreateDefault(); //没有这样的方法,但我希望有这样做的方法吗?
}
对于任何引用类型,默认值是一个空的实例。对于任何类型的值,默认值可以通过 Activator.CreateInstance
获得。但是,当你有一个名为实例
这表明你想要一个的的实际情况的变量,而不是一个空引用......所以,当你的能的做到这一点:
公共对象GetDefaultValue(类型类型)
{
返回type.IsValueType? Activator.CreateInstance(类型):空;
}
...这不是真的清楚这是多么有用的。该是类型的默认的值的,这是不一样的作为默认的实例的类型。
What is the reflective equivalent of :
default(object); //null
When I do not have the type until runtime, e.g.
public void Method(Type type)
{
var instance = type.CreateDefault(); //no such method exists, but I expect there is a way of doing this?
}
For any reference type, the default value is a null instance. For any value type, the default value can be obtained via Activator.CreateInstance
. But when you have a variable called instance
that suggests you want an actual instance rather than a null reference... So while you can do this:
public object GetDefaultValue(Type type)
{
return type.IsValueType ? Activator.CreateInstance(type) : null;
}
... it's not really clear how useful this is. The is the default value of the type, which isn't the same as a default instance of the type.
这篇关于创建类型的默认实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!