有没有办法使用反射在结构实例上设置属性? [英] Is there a way to set properties on struct instances using reflection?
问题描述
我正在尝试编写一些代码来设置结构上的属性(重要的是它是结构上的属性)并且它失败了:
I'm trying to write some code that sets a property on a struct (important that it's a property on a struct) and it's failing:
System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle();
PropertyInfo propertyInfo = typeof(System.Drawing.Rectangle).GetProperty("Height");
propertyInfo.SetValue(rectangle, 5, null);
高度值(由调试器报告)永远不会设置为任何值 - 它保持默认值 0.
The Height value (as reported by the debugger) never gets set to anything - it stays at the default value of 0.
我之前对课程进行了大量反思,并且效果很好.另外,我知道在处理结构时,如果设置字段,则需要使用 FieldInfo.SetValueDirect,但我不知道 PropertyInfo 的等效项.
I have done plenty of reflection on classes before and this has worked fine. Also, I know that when dealing with structs, you need to use FieldInfo.SetValueDirect if setting a field, but I don't know of an equivalent for PropertyInfo.
推荐答案
rectangle
的值被装箱 - 但随后您丢失了装箱的值,也就是正在修改的值.试试这个:
The value of rectangle
is being boxed - but then you're losing the boxed value, which is what's being modified. Try this:
Rectangle rectangle = new Rectangle();
PropertyInfo propertyInfo = typeof(Rectangle).GetProperty("Height");
object boxed = rectangle;
propertyInfo.SetValue(boxed, 5, null);
rectangle = (Rectangle) boxed;
这篇关于有没有办法使用反射在结构实例上设置属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!