我尝试动态设置Nullable <>属性。通过反射设置属性Nullable <>
我把我的财产例如:
PropertyInfo property = class.GetProperty("PropertyName"); // My property is Nullable<> at this time So the type could be a string or int
我想通过反射像
property.SetValue(class,"1256",null);
设置我的财产,我的属性是可空<>一般它不工作。所以我试图找到一种方法来设置我的财产。
知道我执行
Nullable.GetUnderlyingType(property.PropertyType)
任何想法,我可空<>属性的类型?
我尝试创建我可空<>属性的实例与
VAR nullVar = Activator.CreateInstance(typeof运算(可空<>)。MakeGenericType(新类型[] {Nullable.GetUnderlyingType(财产。财产种类) }));
但nullVar总是空
当您设置一个整数,而不是字符串是否行得通? '“1256”是一个字符串,不是一个整数。 – 2009-09-28 18:51:13
它会工作,但重点是我不知道可空属性的类型。我可以使用Nullable.GetUnderlyingType(property.PropertyType)获得类型 – 2009-09-28 18:57:09
'Nullable <>'不能使用'string'作为基础类型,因为'string'是一个引用类型。换句话说'typeof(Nullable <>)。MakeGenericType(t);'如果使用't == typeof(int)''会很好,但是会爆炸(不符合约束)'t == typeof(string) 。所以'Nullable <>'不会以任何方式作为参考类型和可为空值类型的一种“通用类型”。 – 2017-10-04 20:27:11