Is there a way for an attribute that has been applied to a method to know what method it was applied to at run time?
[AttributeUsage(AttributeTargets.Method)]
public class 开发者_如何学编程CustomAttribute : Attribute {}
public class Foo
{
[Custom]
public void Method() {}
}
Then I query the attribute at run time
var attribute = typeof(Foo)
.GetMethod("Method")
.GetCustomAttributes(false)
.OfType<CustomAttribute>()
.First();
Can "attribute" tell it was applied to the "Method" method on the "Foo" class?
I believe not, but if it could it would not be helpful.
I'll explain.
Attributes are only created once you query for them. If you just open a dll, none of the attributes that you added will be created. You will first have to get a pointer to the object that the attributes apply to, and then, once you ask for it's attributes, the .net framework will create them for you. So by the time they are instantiated and your code gets to evaluate them you already know what they apply to.
Because of this, I believe it is reccommended to not put too much magic in the attributes themselves.
Not in a built-in fashion. If an attribute contains method logic that requires knowledge of what it's decorating, the method should take a MemberInfo parameter (or a more derived type like MethodInfo, PropertyInfo, FieldInfo etc.), or an Object if the instance should be passed directly. Then, when invoking the logic on the attribute, it can be given the instance, or the appropriate metadata class, from which it was gotten by the controlling code in the first place.
精彩评论