使用 MethodCall 表达式调用 Attribute.GetCustomAttributes
本文关键字:Attribute GetCustomAttributes 调用 表达式 MethodCall 使用 | 更新日期: 2023-09-27 18:30:25
我正在尝试创建一个带有表达式树的委托,用于读取自定义属性。示例代码为
[AttributeUsage(AttributeTargets.Class)]
public class TestAttribute : Attribute
{
public string Description { get; set; }
}
[TestAttribute(Description="sample text")]
public class TestClass
{
}
我想使用 Func 委托获取描述属性值。我想通过在运行时创建此委托的表达式来实现这一点。所以我试着写一些类似的东西
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() 方法呢?
试试这个:
MethodCallExpression getAttributesMethod = Expression.Call(typeof(Attribute),
"GetCustomAttributes", null, Expression.Constant(typeof(T)));
但是你为什么要返回Func<T, string>
?在委托调用中使用什么作为参数?
这里实际上是这个反射块:
typeof(Attribute).GetMethod("GetCustomAttributes")
如果存在重载并且您未指定参数类型,GetMethod
将引发该异常。
尝试:
typeof(Attribute).GetMethod("GetCustomAttributes", new [] {typeof(MemberInfo)})