AuthenticationRequired

AuthenticationRequired

我创建了这个注释类
这个例子可能没有意义,因为它总是会抛出异常,但是我仍在使用它,因为我只是想解释我的问题是什么。
由于某些原因,我的注释从未被调用过任何解决方案?

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
}

最佳答案



这是对属性的一种误解。有效地存在属性以将元数据添加到代码的某些部分(类,属性,字段,方法,参数等)。编译器将属性中的信息放入并将其烘焙到IL中,并在吃完源代码后吐出代码。

除非有人使用属性,否则属性本身不会做任何事情。也就是说,某人必须在某个时候发现您的属性,然后对其进行操作。它们位于您程序集的IL中,但是除非有人找到它们并对它们执行操作,否则它们不会做任何事情。只有他们这样做时,实例化属性的实例。实现此目的的典型方法是使用反射。

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

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

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

10-06 12:19