C# - 使用自定义注释?
我创建了这个注释类
这个例子可能没有意义,因为它总是会抛出异常,但我仍在使用它,因为我只是试图解释我的问题是什么。 由于某些原因我的注释永远不会被调用,有什么解决方案吗?
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
}
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("Throw this to see if annotation works or not");
}
}
[AuthenticationRequired]
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// My break point get here
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是对属性的一种误解。属性的存在实际上是为了将元数据添加到代码的某些部分(类、属性、字段、方法、参数等)。编译器获取属性中的信息,并将其烘焙到 IL 中,IL 会在处理完源代码后吐出。代码。
属性本身不会做任何事情,除非有人使用它们。也就是说,有人必须在某个时候发现你的属性,然后对其采取行动。它们位于程序集的 IL 中,但除非有人找到它们并对其采取行动,否则它们不会执行任何操作。只有当他们这样做时,属性的实例才会被实例化。执行此操作的典型方法是使用反射。
要在运行时获取属性,您必须这样说
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