Hello guys,
Due to special requirements, I must create my own
serialization/deserialization solution using .Net2.0. The idea looks straight
forward: I use Reflection to navigate through the objects and get/set their
fields (and also add/retrieve my own special stuff). However,
FieldInfo.Set(object obj, object value) does not work on Structs (see sample
code below). If I understand the things right, the underlying reason is that
structs are value types and passed by value. So in the body of FieldInfo.Set,
a copy of the input struct is set, while the original one outside the method
remains intact. Do you have any idea, how to overcome the issue? How does
BinarySerializer do that?
Here is an example:
System.Drawing.Point p = new System.Drawing.Point(10, 20);
FieldInfo xField = p.GetType().GetField("x", BindingFlags.Instance |
BindingFlags.NonPublic);
xField.SetValue(p, 100);
Console.WriteLine(p.X); // Still returns 10
Thanx in advance!
Jon Skeet [C# MVP] - 27 Feb 2008 16:32 GMT
> Due to special requirements, I must create my own
> serialization/deserialization solution using .Net2.0. The idea looks straight
[quoted text clipped - 15 lines]
> xField.SetValue(p, 100);
> Console.WriteLine(p.X); // Still returns 10
Try this (untested):
System.Drawing.Point p = new System.Drawing.Point(10, 20);
FieldInfo xField = p.GetType().GetField("x", BindingFlags.Instance |
BindingFlags.NonPublic);
object[] boxed = new object[] {p};
xField.SetValue(boxed[0], 100);
p = (Point)boxed[0];
Console.WriteLine(p.X); // Still returns 10

Signature
Jon Skeet - <skeet@pobox.com>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk