我正在尝试使用表达式树创建一个委托来读取自定义属性。示例代码是
[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() 方法呢?