C# - 使用自定义注释?

ary*_*axt 12 c# annotations

我创建了这个Annotation类
这个例子可能没有意义,因为它总是抛出一个异常,但我仍在使用它,因为我只是想解释我的问题是什么.我的注释永远不会因某些原因而被调用?

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

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

jas*_*son 24

我的注释永远不会因某些原因而被调用?

这是对属性的误解.有效地存在属性以将元数据添加到代码的某些部分(类,属性,字段,方法,参数等).编译器获取属性中的信息并将其烘焙到IL中,当它完成吃源时它会吐出码.

除非有人使用属性,否则属性本身不会做任何事情.也就是说,某人必须在某个时刻发现您的属性,然后对其采取行动.他们坐在你的集会的IL中,但除非有人发现并对他们采取行动,否则他们不做任何事情.只有当他们这样做时才会实例化属性的实例.执行此操作的典型方法是使用反射.

要在运行时获取属性,您必须说出类似的内容

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

foreach(var attribute in attributes) {
    Console.WriteLine(attribute.ToString());
}
Run Code Online (Sandbox Code Playgroud)

  • @aryaxt:是的,可以这样做.但是你需要为你构建一些东西(你可以自己做,但有一些工具可以为你做).您正在寻找的是能够为您动态构建代理的东西.这些问题通常被称为跨领域问题,这种类型的编程称为面向方面编程.如果你看一下在温莎城堡的拦截能力,例如,你会看到它是如何做到:http://www.castleproject.org/container/documentation/trunk/usersguide/interceptors.html (2认同)