我正在尝试创建一个带有表达式的委托来读取自定义属性。示例代码是
[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()方法?
答案 0 :(得分:0)
这实际上就是这个反思块:
typeof(Attribute).GetMethod("GetCustomAttributes")
GetMethod
如果存在重载并且您没有指定参数类型,则会抛出该异常。
尝试:
typeof(Attribute).GetMethod("GetCustomAttributes", new [] {typeof(MemberInfo)})
答案 1 :(得分:0)
试试这个:
MethodCallExpression getAttributesMethod = Expression.Call(typeof(Attribute),
"GetCustomAttributes", null, Expression.Constant(typeof(T)));
但为什么要归还Func<T, string>
?你在委托调用中用什么作为参数?