C#-使用自定义注释?
我创建了这个注释类C#-使用自定义注释?,c#,annotations,C#,Annotations,我创建了这个注释类 这个例子可能没有意义,因为它总是抛出一个异常,但我仍然在使用它,因为我只是试图解释我的问题是什么。 由于某些原因,我的注释从未被调用过。有什么解决方案吗 public class AuthenticationRequired : System.Attribute { public AuthenticationRequired() { // My break point never gets hit why? throw new Except
这个例子可能没有意义,因为它总是抛出一个异常,但我仍然在使用它,因为我只是试图解释我的问题是什么。 由于某些原因,我的注释从未被调用过。有什么解决方案吗
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
}
由于某些原因,我的注释从未被调用过。有什么解决方案吗
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中,当它吃掉源代码时,会将其吐出
属性本身不起任何作用,除非有人使用它们。也就是说,某个人在某个时候必须发现你的属性,然后对它采取行动。他们坐在你们大会的中间,但除非有人发现他们并对他们采取行动,否则他们什么也不会做。只有当他们这样做时,属性的实例才会被实例化。实现这一点的典型方法是使用反射
要在运行时获取属性,您必须说
var attributes = typeof(Foo)
.GetMethod("Window_Loaded")
.GetCustomAttributes(typeof(AuthenticationRequired), true)
.Cast<AuthenticationRequired>();
foreach(var attribute in attributes) {
Console.WriteLine(attribute.ToString());
}
var attributes=typeof(Foo)
.GetMethod(“已加载窗口”)
.GetCustomAttributes(typeof(AuthenticationRequired),true)
.Cast();
foreach(属性中的var属性){
Console.WriteLine(attribute.ToString());
}
在这里,您可以了解如何访问和阅读自定义注释:很抱歉,如果无法编译,我手头没有编译器。感谢您的回答,是否可以使其在方法具有特定属性时调用特定的代码块?那会被认为是坏习惯吗?假设我希望每个具有“Log”属性的方法都记录时间。我正在尝试使用这种方法来重用code@aryaxt:是的,这是可能的。但是你需要一些东西来为你构建它(你可以自己做,但是有一些工具可以为你做)。您正在寻找的是能够动态地为您构建代理的东西。这些关注点通常称为横切关注点,这种类型的编程称为面向方面编程。例如,如果你看看温莎城堡的拦截能力,你会发现它是如何做到的:@jason链接断了。你有办法吗?