未找到属性的属性

时间:2013-03-20 18:26:17

标签: c# reflection

[MyAttribute("x")]
public string Z{get;set;}

[MyAttribute("x")]
public void Y()
{

}

它找到方法上的attr就好了,但是属性上的那个没有被识别。

public static bool HasAttribute(this MethodInfo m, Type attrType)
{
    return Attribute.IsDefined(m, attrType);
}

我在调试期间查看了对象,并且在方法中它正确地列出了CustomAttributes中的属性,但是属性上的属性是空的......有人可以解释一下吗?

1 个答案:

答案 0 :(得分:2)

您在属性上定义了属性,而不是在属性访问器上定义了属性。要在getter上提供属性,您将使用此语法(我包括所有3个可能的位置,您可以选择根据其适用性在任何组合上添加属性)。

[MyAttribute("on PropertyInfo")]
public string Z
{
    [MyAttribute("on getter MethodInfo")] get;
    [MyAttribute("on setter MethodInfo")] set;
}