有没有一种方法来设置使用反射结构实例的属性? [英] Is there a way to set properties on struct instances using reflection?

查看:162
本文介绍了有没有一种方法来设置使用反射结构实例的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试着写一些code,设置在结构(重要的是,它是在一个结构属性)的属性和它的失败:

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.

推荐答案

长方形的值被装箱 - 但你失去的是盒装的价值,这是什么东西被修改。试试这个:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆