Created
May 19, 2021 21:12
-
-
Save pardeike/79174e80d4c43d861e55ed9c88915901 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// use with LINQPad | |
void Main() | |
{ | |
var f = new Foo(); | |
var n1 = Traverse.Create(f).Field("bar").Field("n").GetValue<int>(); | |
Console.WriteLine($"n1={n1}"); | |
// does not work because `Field("bar") returns a copy of the struct | |
Traverse.Create(f).Field("bar").Field("n").SetValue(456); | |
// | |
var n2 = Traverse.Create(f).Field("bar").Field("n").GetValue<int>(); | |
Console.WriteLine($"n2={n2}"); | |
// works because it gets a copy of the struct, updates it and writes it back | |
var bar = Traverse.Create(f).Field("bar"); | |
var b = bar.GetValue(); | |
Traverse.Create(b).Field("n").SetValue(789); | |
bar.SetValue(b); | |
var n3 = Traverse.Create(f).Field("bar").Field("n").GetValue<int>(); | |
Console.WriteLine($"n3={n3}"); | |
} | |
public class Foo | |
{ | |
private struct Bar | |
{ | |
int n; | |
public Bar(int n) | |
{ | |
this.n = n; | |
} | |
} | |
private Bar bar; | |
public Foo() | |
{ | |
bar = new Bar(123); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment