Generate dynamic method to set a field of a struct instead of using reflection

前端 未结 6 1166
温柔的废话
温柔的废话 2020-12-08 12:19

Let\'s say I have the following code which update a field of a struct using reflection. Since the struct instance is copied into the DynamicUpdate

6条回答
  •  温柔的废话
    2020-12-08 12:40

    This code works for structs without using ref:

    private Action CreateSetter(FieldInfo field)
    {
        var instance = Expression.Parameter(typeof(object));
        var value = Expression.Parameter(typeof(object));
    
        var body =
            Expression.Block(typeof(void),
                Expression.Assign(
                    Expression.Field(
                        Expression.Unbox(instance, field.DeclaringType),
                        field),
                    Expression.Convert(value, field.FieldType)));
    
        return (Action)Expression.Lambda(body, instance, value).Compile();
    }
    

    Here is my test code:

    public struct MockStruct
    {
        public int[] Values;
    }
    
    [TestMethod]
    public void MyTestMethod()
    {
        var field = typeof(MockStruct).GetField(nameof(MockStruct.Values));
        var setter = CreateSetter(field);
        object mock = new MockStruct(); //note the boxing here. 
        setter(mock, new[] { 1, 2, 3 });
        var result = ((MockStruct)mock).Values; 
        Assert.IsNotNull(result);
        Assert.IsTrue(new[] { 1, 2, 3 }.SequenceEqual(result));
    }
    

提交回复
热议问题