有没有办法使用反射来设置结构实例的属性?
我正在尝试编写一些在结构上设置属性的代码(重要的是它是结构上的属性)并且失败:
System.Drawing.Rectangle rectangle = new System.Drawing.Rectangle();
PropertyInfo propertyInfo = typeof(System.Drawing.Rectangle).GetProperty("Height");
propertyInfo.SetValue(rectangle, 5, null);
高度值(如调试器报告的)永远不会设置为任何内容 - 它保持默认值值为 0。
我之前对课程进行了大量反思,效果很好。另外,我知道在处理结构时,如果设置字段,则需要使用 FieldInfo.SetValueDirect,但我不知道 PropertyInfo 的等效项。
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);
The Height value (as reported by the debugger) never gets set to anything - it stays at the default value of 0.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
rectangle
的值正在被装箱 - 但随后您将丢失装箱的值,这就是正在修改的值。试试这个:The value of
rectangle
is being boxed - but then you're losing the boxed value, which is what's being modified. Try this:听说过
SetValueDirect
?他们成功是有原因的。 :)除了未记录的
__makeref
之外,您还可以使用其他方法(请参阅System.TypedReference
),但它们更加痛苦。Ever heard of
SetValueDirect
? There's a reason they made it. :)There's other methods than the undocumented
__makeref
which you could use (seeSystem.TypedReference
) but they're more painful.