【发布时间】:2012-04-01 21:57:22
【问题描述】:
我创建了一个自定义属性,当它被击中时会写入控制台,但它似乎没有被击中。这是微软教程(http://msdn.microsoft.com/en-us/library/sw480ze8.aspx),正在 2010 年运行,.net 4。我猜一定是我做错了,但是我看不出它是什么。有人可以帮忙吗?
这是属性,它的代码永远不会被命中
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct)]
public class Author : Attribute
{
private string _name;
private double _version;
public Author(string name)
{
Console.WriteLine(string.Format("author {0} was just created", name));
_name = name;
_version = 1.0;
}
}
这是使用它的类 - 它成功地在构造函数中写出代码:
/// <summary>
/// TODO: Update summary.
/// </summary>
[Author("P. Ackerman")]
public class Ackerman
{
public Ackerman()
{
Console.WriteLine("I created Ackerman.");
}
}
这是调用它并成功打印出 new Ackerman() 构造函数中的代码的控制台应用程序:
static void Main(string[] args)
{
Ackerman author1 = new Ackerman();
Console.ReadLine();
}
谢谢!!
【问题讨论】:
-
该属性是针对类型定义而不是针对该类型的实例,因此除非您尝试检查它,否则您不会看到调用的属性构造函数
标签: c#-4.0 aop custom-attributes custom-attribute