默认的编程当量(类型) [英] Programmatic equivalent of default(Type)

查看:110
本文介绍了默认的编程当量(类型)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是通过键入的属性反射来循环并设置某些类型的默认。现在,我可以做的类型的交换机,并设置默认(类型)明确,但我宁愿做它在一行。是否有违约的纲领性等价?

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?

推荐答案


  • 在值类型使用的情况下,<一个href=\"http://msdn.microsoft.com/en-us/library/system.activator.createinstance.aspx\">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;
    }
    

    这篇关于默认的编程当量(类型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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