我怎样才能调用默认(T)与类型? [英] How can I call default(T) with a type?
本文介绍了我怎样才能调用默认(T)与类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C#中,我可以使用默认(T)
来获得一个类型的默认值。我需要从的System.Type
获取默认的类型在运行时。我怎样才能做到这一点?
例如。沿着这行的东西(这不工作)
VAR类型= typeof运算(INT);
VAR设置defaultValue =默认值(类型);
解决方案
有关引用类型返回空
,一个值类型,你可以尝试使用 Activator.CreateInstance
或调用类型的默认构造函数。
公共静态对象的默认值(类型类型)
{
如果(type.IsValueType)
{
返回Activator.CreateInstance(类型);
}
返回null;
}
In c# I can use default(T)
to get the default value of a type. I need to get the default type at run time from a System.Type
. How can I do this?
E.g. Something along the lines of this (which doesn't work)
var type = typeof(int);
var defaultValue = default(type);
解决方案
For a reference type return null
, for a value type, you could try using Activator.CreateInstance
or calling the default constructor of the type.
public static object Default(Type type)
{
if(type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}
这篇关于我怎样才能调用默认(T)与类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文