1

我正在尝试使用表达式树创建一个委托来读取自定义属性。示例代码是

 [AttributeUsage(AttributeTargets.Class)]
public class TestAttribute : Attribute
{
    public string Description { get; set; }
}


 [TestAttribute(Description="sample text")]
 public class TestClass
 {
 }

我想使用 Func 委托获取 Description 属性值。我想用在运行时创建这个委托的表达式来实现这一点。所以我试着写一些类似的东西

public  Func<T, string> CreateDelegate<T>()
    {
       //Below is the code which i want to write using expressions
        //TestAttribute attribute = typeof(T).GetCustomAttributes(typeof(TestAttribute), false)[0];
        //return attribute.Description;

        ParameterExpression clazz = Expression.Parameter(typeof(T),"clazz");
        ParameterExpression description = Expression.Variable(typeof(string),"description");
        ParameterExpression attribute=Expression.Variable(typeof(TestAttribute),"attribute");

        MethodCallExpression getAttributesMethod = Expression.Call(typeof(Attribute).GetMethod("GetCustomAttributes"),clazz);

        Expression testAttribute = Expression.TypeAs(Expression.ArrayIndex(getAttributesMethod, Expression.Constant(0)), typeof(TestAttribute));
        BinaryExpression result = Expression.Assign(description, Expression.Property(testAttribute, "Description"));

        BlockExpression body = Expression.Block(new ParameterExpression[] { clazz, attribute,description },
            getAttributesMethod, testAttribute, result);             

        Func<T, string> lambda = Expression.Lambda<Func<T, string>>(body, clazz).Compile();
        return lambda;
    }

但是当我调用这个方法时,我在 getAttributesMethod 行得到了一个 AmbiguousMatchException,它说“找到了不明确的匹配”。那么如何在表达式树中使用 Attribute.GetCustomAttribute() 方法呢?

4

2 回答 2

0

它实际上是这里的反射块:

typeof(Attribute).GetMethod("GetCustomAttributes")

GetMethod如果它有重载并且您没有指定参数类型,则会抛出该异常。

尝试:

typeof(Attribute).GetMethod("GetCustomAttributes", new [] {typeof(MemberInfo)})
于 2012-04-09T12:51:29.543 回答
0

试试这个:

MethodCallExpression getAttributesMethod = Expression.Call(typeof(Attribute),
    "GetCustomAttributes", null, Expression.Constant(typeof(T)));

但是你为什么要返回一个Func<T, string>?您在委托调用中使用什么作为参数?

于 2012-04-09T16:32:53.853 回答