Custom Attribute not being hit

◇◆丶佛笑我妖孽 提交于 2019-12-20 05:04:48

问题


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.");
    }
}

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();
    }

Thanks!!


回答1:


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);

This code will trigger your Console.WriteLine(string.Format("author {0} was just created", name));



来源:https://stackoverflow.com/questions/9735889/custom-attribute-not-being-hit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!