问题描述
我创建了一个自定义属性,当它被击中时写入控制台,但它似乎没有被击中.这是微软教程 (http://msdn.microsoft.com/en-us/library/sw480ze8.aspx) 并且正在 2010 年运行,.net 4.我猜一定是我做错了什么,但是我看不出它是什么.有人可以帮忙吗?
I've created a custom attribute which writes to the console when it's hit, however it doesn't seem to be hit. It's the microsoft tutorial (http://msdn.microsoft.com/en-us/library/sw480ze8.aspx) and is being run on 2010, .net 4. I'm guessing it must be me that's doing something wrong, but I can't see what it is. Can anyone help?
这是一个属性,它的代码永远不会被命中
This is the attribute, whose code is never being hit
[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;
}
}
这是使用它的类 - 它成功地在构造函数中写出代码:
This is the class that uses it - it's successfully writing out the code in the constructor:
/// <summary>
/// TODO: Update summary.
/// </summary>
[Author("P. Ackerman")]
public class Ackerman
{
public Ackerman()
{
Console.WriteLine("I created Ackerman.");
}
}
这是调用它并成功打印出 new Ackerman() 构造函数中的代码的控制台应用程序:
And this is the console app that calls it and is successfully printing out the code in the new Ackerman() constructor:
static void Main(string[] args)
{
Ackerman author1 = new Ackerman();
Console.ReadLine();
}
谢谢!!
推荐答案
不创建类的属性实例,然后创建类的实例.只有这样你才会像这样特别要求他们:
Instances of attributes on class are not created then you create instance of class. Only then you specifically asks for them like this:
var attrib = author1.GetType().GetCustomAttributes(false);
此代码将触发您的Console.WriteLine(string.Format("author {0} was just created", name));
这篇关于未命中自定义属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!