Last active
August 30, 2022 12:22
-
-
Save mgravell/ee4b8f59e8e4380c951271f1a55483ca to your computer and use it in GitHub Desktop.
This file contains 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
using System.Linq.Expressions; | |
using System.Reflection; | |
using System; | |
static class P | |
{ | |
class Foo | |
{ | |
public Guid Value => _value; | |
private readonly Guid _value; | |
public Foo(Guid value) => _value = value; | |
} | |
static void Main() | |
{ | |
var clone = Expression.Parameter(typeof(Foo), "clone"); | |
var value = Expression.Parameter(typeof(Guid), "value"); | |
var fieldInfo = typeof(Foo).GetField("_value", BindingFlags.NonPublic | BindingFlags.Instance); | |
// ** what we broadly want - but the Expression API disallows because of init-only | |
// "Expression must be writeable (Parameter 'left')" | |
// var body = Expression.Assign(Expression.Field(clone, fieldInfo), value); | |
// long-winded and inefficient way of doing the same thing | |
var expression = Expression.Convert(value, typeof(object)); | |
var body = Expression.Call(Expression.Constant(fieldInfo), fieldSetValue, clone, expression); | |
var action = Expression.Lambda<Action<Foo, Guid>>(body, clone, value).Compile(); | |
var obj = new Foo(Guid.NewGuid()); | |
var newGuid = Guid.NewGuid(); | |
Console.WriteLine($"original: {obj.Value}; pushing {newGuid}"); | |
action(obj, newGuid); | |
Console.WriteLine($"final: {obj.Value}"); | |
} | |
static readonly MethodInfo fieldSetValue = typeof(FieldInfo).GetMethod(nameof(FieldInfo.SetValue), new[] { typeof(object), typeof(object) }); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@neerajsahani-logianalytics "I am not sure of the purpose to use an array of fieldinfo." - well, that's your code, not mine - I don't use an array; I can't say anything about your code without being able to see your code