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!!

有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top