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

前端 未结 6 1167
温柔的废话
温柔的废话 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:53

    EDIT again: This works structs now.

    There's a gorgeous way to do it in C# 4, but you'll have to write your own ILGenerator emit code for anything before that. They added an ExpressionType.Assign to the .NET Framework 4.

    This works in C# 4 (tested):

    public delegate void ByRefStructAction(ref SomeType instance, object value);
    
    private static ByRefStructAction BuildSetter(FieldInfo field)
    {
        ParameterExpression instance = Expression.Parameter(typeof(SomeType).MakeByRefType(), "instance");
        ParameterExpression value = Expression.Parameter(typeof(object), "value");
    
        Expression expr =
            Expression.Lambda(
                Expression.Assign(
                    Expression.Field(instance, field),
                    Expression.Convert(value, field.FieldType)),
                instance,
                value);
    
        return expr.Compile();
    }
    

    Edit: Here was my test code.

    public struct SomeType
    {
        public int member;
    }
    
    [TestMethod]
    public void TestIL()
    {
        FieldInfo field = typeof(SomeType).GetField("member");
        var setter = BuildSetter(field);
        SomeType instance = new SomeType();
        int value = 12;
        setter(ref instance, value);
        Assert.AreEqual(value, instance.member);
    }
    

提交回复
热议问题