如何设置通过反射码(C#)空类型? [英] how to set nullable type via reflection code ( c#)?

查看:107
本文介绍了如何设置通过反射码(C#)空类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用反射来设置一个类的属性。



我有一个词典<字符串,字符串> 与属性名称和字符串值。



里面的反映循环,我需要将字符串值转换为相应的属性类型,同时设置每个属性的值。一些属性类型是可空类型。




  1. 如何从的PropertyInfo知道这个属性是可空类型?

  2. 如何使用反射设置可空类型



编辑:
在这个博客的评论中定义的第一个方法,似乎这样的伎俩,以及:
http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx


解决方案

  1. 做到这一点的方法之一是:

      type.GetGenericTypeDefinition ()== typeof运算(可空<>)


  2. 只需设置是根据任何其他反射代码:

      propertyInfo.SetValue(yourObject,yourValue); 



I need to set the properties of a class using reflection.

I have a Dictionary<string,string> with property names and string values.

Inside a reflection loop, I need to convert the string value to the appropriate property type while setting the value for each property. Some of these property types are nullable types.

  1. How can I know from PropertyInfo if the property is a nullable type?
  2. How can I set a nullable type using reflection?

edit: The first method defined in the comments on this blog seems to do the trick as well: http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx

解决方案

  1. One way to do this is:

    type.GetGenericTypeDefinition() == typeof(Nullable<>)
    

  2. Just set is as per any other reflection code:

    propertyInfo.SetValue(yourObject, yourValue);
    

这篇关于如何设置通过反射码(C#)空类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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