C# 如何在Windows Phone 7中的对象上设置结构类型的字段

C# 如何在Windows Phone 7中的对象上设置结构类型的字段,c#,reflection,boxing,fieldinfo,C#,Reflection,Boxing,Fieldinfo,我在Windows Phone 7应用程序中的对象上设置字段时遇到问题(我怀疑它与compact框架有关,而不是特定于Windows Phone 7)。我认为这是特定于设置struct类型的值。我通常使用以下方法: // fieldName is the name of the field I'm interested in setting FieldInfo fieldInfo = target.GetType().GetField(fieldName); // target is the

我在Windows Phone 7应用程序中的对象上设置字段时遇到问题(我怀疑它与compact框架有关,而不是特定于Windows Phone 7)。我认为这是特定于设置
struct
类型的值。我通常使用以下方法:

// fieldName is the name of the field I'm interested in setting
FieldInfo fieldInfo = target.GetType().GetField(fieldName);

// target is the object I'm setting the value on
// value is the value that I am setting
fieldInfo.SetValueDirect(__makeref(target), value);

不幸的是,Windows Phone 7上不存在
SetValueDirect
,简单地使用
SetValueDirect
对目标没有任何作用。是否有其他方法通过反射在WP7上设置
struct
字段?

您必须对结构进行装箱,使用SetValue、和unbox。不是很优雅,但另一个很好的理由是结构通常应该是只读的。目前,您可能忽略了最后一步(通过使用隐式方框而不捕获方框,您对方框值所做的更改将被放弃)。视觉上:

MyStruct val = ...
object boxedVal = val;
fieldInfo.SetValue(boxedVal, newValue);
val = (MyStruct)boxedVal;
更一般地说,CF上的元编程相当薄弱。如果您正在进行大量的元编程,那么可以通过完整的.NET提前进行元编程,检查CF程序集并生成封装所需功能的CF程序集。为此,我成功地使用了IKVM.Reflection(内置的.NET反射无法做到这一点)