如何设置通过反射码(C#)空类型? [英] how to set nullable type via reflection code ( c#)?
问题描述
我需要使用反射来设置一个类的属性。
我有一个词典<字符串,字符串>
与属性名称和字符串值。
里面的反映循环,我需要将字符串值转换为相应的属性类型,同时设置每个属性的值。一些属性类型是可空类型。
- 如何从的PropertyInfo知道这个属性是可空类型?
- 如何使用反射设置可空类型
编辑:
在这个博客的评论中定义的第一个方法,似乎这样的伎俩,以及:
的 http://weblogs.asp.net/pjohnson/archive/2006/02/07/437631.aspx
-
做到这一点的方法之一是:
type.GetGenericTypeDefinition ()== typeof运算(可空<>)
-
只需设置是根据任何其他反射代码:
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.
- How can I know from PropertyInfo if the property is a nullable type?
- 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
One way to do this is:
type.GetGenericTypeDefinition() == typeof(Nullable<>)
Just set is as per any other reflection code:
propertyInfo.SetValue(yourObject, yourValue);
这篇关于如何设置通过反射码(C#)空类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!