default(Type) 的编程等效项 [英] Programmatic equivalent of default(Type)

查看:16
本文介绍了default(Type) 的编程等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用反射来遍历 Type 的属性并将某些类型设置为其默认值.现在,我可以切换类型并显式设置 default(Type),但我宁愿在一行中进行.是否有程序等效的默认值?

I'm using reflection to loop through a Type's properties and set certain types to their default. Now, I could do a switch on the type and set the default(Type) explicitly, but I'd rather do it in one line. Is there a programmatic equivalent of default?

推荐答案

  • 如果是值类型,请使用 Activator.CreateInstance 它应该可以正常工作.
  • 使用引用类型时只返回 null
    • In case of a value type use Activator.CreateInstance and it should work fine.
    • When using reference type just return null
    • public static object GetDefault(Type type)
      {
         if(type.IsValueType)
         {
            return Activator.CreateInstance(type);
         }
         return null;
      }
      

      在.net标准等较新版本的.net中,type.IsValueType需要写成type.GetTypeInfo().IsValueType

      In the newer version of .net such as .net standard, type.IsValueType needs to be written as type.GetTypeInfo().IsValueType

      这篇关于default(Type) 的编程等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆