自定义属性未命中 [英] Custom Attribute not being hit
问题描述
我创建了一个自定义属性,当它被击中时写入控制台,但它似乎没有被击中。这是微软教程(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.");
}
}
这是调用它的控制台应用程序,成功打印出新的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 {0}刚刚创建,name));
这篇关于自定义属性未命中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!