开发者

C# - Using Custom Annotations?

I created this Annotation class

This example might not make sense because It'll always throw an exception but I'm still using it as I am just trying to explain what my question is. My annotation never gets called for some reasons any solutions?

public class AuthenticationRequired : System.Attribute
{
   public AuthenticationRequired()
   {
      // My break point never gets hit why?
      throw new Exception("T开发者_StackOverflowhrow this to see if annotation works or not");
   }
}

[AuthenticationRequired]
private void Window_Loaded(object sender, RoutedEventArgs e)
{
   // My break point get here
}


My annotation never gets called for some reasons any solutions?

This is kind of a misunderstanding of attributes. Attributes effectively exist to add metadata to certain parts of your code (classes, properties, fields, methods, parameters, etc.) The compiler takes the information in the attribute and bakes it into the IL that it spits out when it's done eating your source code.

Attributes by themselves don't do anything unless someone consumes them. That is, someone at some point has to discover your attribute and then take action on it. They sit in the IL of your assembly, but they don't do anything unless someone finds them and acts on them. It's only when they do this will an instance of the attribute be instantiated. The typical way to do this is using reflection.

To obtain the attributes at runtime, you have to say something like

var attributes = typeof(Foo)
                    .GetMethod("Window_Loaded")
                    .GetCustomAttributes(typeof(AuthenticationRequired), true)
                    .Cast<AuthenticationRequired>();

foreach(var attribute in attributes) {
    Console.WriteLine(attribute.ToString());
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜