Delegate.CreateDelegate中的BindFailure用于struct的属性

时间:2015-04-10 17:50:53

标签: c# linq-expressions

为什么在实现类型是结构时,为属性的GetMethod创建已编译的委托会引发以下争论?

ArgumentException: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.

我在SO上找到了一个few posts处理类似问题,其中func-type不正确。但是,我无法看到我在这里做错了什么。

通过使用Lambdaexpression创建的委托访问该属性可以正常工作。将struct更改为class也是如此。

完整的演示程序(不在.net-Fiddle中运行)

using System;
using System.Linq.Expressions;
using System.Reflection;

public class Program
{
    public static void Main()
    {
        PropertyInfo propInfo = typeof (TestStruct).GetProperty("Property");


        TestStruct value = new TestStruct
        {
            Property = "Hello World!!1 from Reflection"
        };


        // This doesnt work
        try
        {
            Func<TestStruct,string> functionFromRelfection = (Func<TestStruct,string>) Delegate.CreateDelegate(typeof (Func<TestStruct,string>), propInfo.GetGetMethod());
            Console.WriteLine(functionFromRelfection(value));
        }
        catch (Exception e)
        {
             // Breakpoint goes here
        }

        value = new TestStruct
        {
            Property = "Hello World!!1 from Expression"
        };

        // This works
        ParameterExpression parameter = Expression.Parameter(typeof(TestStruct));
        MemberExpression member = Expression.Property(parameter, propInfo);

        LambdaExpression lambda = Expression.Lambda<Func<TestStruct, string>>(member, parameter);

        Func<TestStruct, string> functionFromExpression = (Func<TestStruct, string>)lambda.Compile();
        Console.WriteLine(functionFromExpression(value));

        Console.ReadKey();
    }

    public struct TestStruct
    {
        public string Property { get; set; }
    }
}

0 个答案:

没有答案