我正在使用反射来循环Type
的属性并将某些类型设置为其默认值。现在,我可以切换类型并设置default(Type)
明确地,但我宁愿在一行中完成。是否存在与默认值等效的编程方式?
- 如果是值类型使用激活器.CreateInstance http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx它应该工作正常。
- 使用引用类型时只需返回 null
public static object GetDefault(Type type)
{
if(type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}
在较新版本的 .net(例如 .net 标准)中,type.IsValueType
需要写成type.GetTypeInfo().IsValueType
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)