.NET - 用于反射的PropertyInfo获取默认值反射、默认值、NET、PropertyInfo

2023-09-02 10:43:45 作者:我有孤独与酒你跟不跟我走

这是今天真的绊倒了我。我敢肯定,它并不难,但我有一个System.Reflection.PropertyInfo对象。我想设置基于数据库查询的结果它的价值(考虑ORM,映射列回属性)。

This is really stumping me today. I'm sure its not that hard, but I have a System.Reflection.PropertyInfo object. I want to set its value based on the result of a database lookup (think ORM, mapping a column back to a property).

我的问题是,如果数据库返回的值是为DBNull,我只是想将属性值设置为默认值,与调用:

My problem is if the DB returned value is DBNull, I just want to set the property value to its default, the same as calling:

value = default(T);  // where T is the type of the property.

不过,如果你给它一个类型,默认()方法将不会编译这是我有:

However, the default() method won't compile if you give it a Type, which is what I have:

object myObj = ???; // doesn't really matter. some arbitrary class.
PropertyInfo myPropInf = ???; // the reflection data for a property on the myObj object.
myPropInf.SetValue(myObj, default(myPropInf.PropertyType), null);

以上不能编译。默认(Type)为无效。我也想过这样做的:

The above doesn't compile. default(Type) is invalid. I also thought about doing:

object myObj = ???;
PropertyInfo myPropInf = ???;
myPropInf.SetValue(myObj, Activator.CreateInstance(myPropInf.PropertyType), null);

然而,如果类型为字符串,将分配值新的String(),但我真的想空,这是默认值(字符串)将返回。

However, if the Type is string, that would assign the value "new String()", but I really want "null", which is what "default(string)" would return.

那么,我在这里丢失? 我想一个真正哈克的方法是创建一个MyObj中的类型的新实例,复制属性过,但似乎只是愚蠢的......

So what am I missing here? I suppose a really hacky way would be to create a new instance of myObj's Type and copy the property over, but that just seems stupid...

object myObj = ???;
PropertyInfo  myPropInf = ???;
var blank = Activator.CreateInstance(myObj.GetType());
object defaultValue = myPropInf.GetValue(blank, null);
myPropInf.SetValue(myObj, defaultValue, null);

我宁愿不浪费内存,打造了一个全新的实例,只是为了得到默认的属性,虽然。似乎很浪费的。

I'd rather not waste the memory to make a whole new instance, just to get the default for the property though. Seems very wasteful.

任何想法?

推荐答案

我相信,如果你只是做

prop.SetValue(obj,null,null);

如果它是一个值类型,它会设置为默认值,如果它是一个引用类型,它会设置为null。

If it's a valuetype, it'll set it to the default value, if it's a reference type, it'll set it to null.