Question

I am having trouble setting a field on an object in a Windows Phone 7 app (I suspect it's related to the compact framework, and not specific to Windows Phone 7). I believe this is specific to setting values that are of struct types. Normally I use the following:

// 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);

Unfortunately SetValueDirect doesn't exist on Windows Phone 7, and simply using SetValue doesn't do anything to target. Is there an alternative way to set struct fields on WP7 through reflection?

Was it helpful?

Solution

You would have to box the struct, use SetValue, and unbox. Not very elegant, but another good reason that structs should generally be read-only. Currently you are presumably omitting the last step (by using an implicit box without capturing the box, do your change to the boxed value is discarded). Visually:

MyStruct val = ...
object boxedVal = val;
fieldInfo.SetValue(boxedVal, newValue);
val = (MyStruct)boxedVal;

More generally, meta-programming is rather weak on CF. If you are doing lots of this, there are ways to do the meta-programming in advance via full .NET, inspecting a CF assembly and generating a CF assembly that encapsulates the functionality you need. I've had success using IKVM.Reflection for this purpose (th inbuilt .NET reflection cannot do this).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top