属性上的 SetValue 不会更新对象
我不明白为什么这不起作用。谁能向我解释为什么 SetValue 不设置我的对象属性的值?
T row = new T();
foreach (PropertyInfo property in row.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
Field[] dbFields = property.GetCustomAttributes(typeof(Field), false) as Field[];
Object obj = (Int32)1000; // Arbitrary Value;
Object castObj = Convert.ChangeType(obj, property.PropertyType);
property.SetValue(row, castObj, null); // DOES NOT UPDATE row!! WHY!?
}
任何帮助表示赞赏。
I cannot figure out why this is not working. Can anyone explain to me why SetValue does not set the value of my object's properties?
T row = new T();
foreach (PropertyInfo property in row.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
Field[] dbFields = property.GetCustomAttributes(typeof(Field), false) as Field[];
Object obj = (Int32)1000; // Arbitrary Value;
Object castObj = Convert.ChangeType(obj, property.PropertyType);
property.SetValue(row, castObj, null); // DOES NOT UPDATE row!! WHY!?
}
Any help is appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只要
T
是引用类型(类),它就应该可以正常工作。如果T
是值类型(结构),它将无法按原样工作。每次调用property.SetValue
时,该值都会被装箱,并且现有值将保持不变。有可能这就是问题所在吗?如果是这样,我建议您首先避免编写可变值类型 - 考虑将其设为引用类型。您可以只强制将其装箱一次,然后在最后拆箱一次 - 但如果我是你,我会避开可变值类型。
It should work fine so long as
T
is a reference type (a class). It won't work as-is ifT
is a value type (a struct). The value will be boxed on each call toproperty.SetValue
, and the existing value would remain untouched. Is it possible that that's the problem? If so, I'd urge you to avoid writing mutable value types in the first place - consider making it a reference type instead.You could just force it to be boxed once, then unboxed once at the end - but if I were you I'd just steer well clear of mutable value types.