Am Fri, 06 Apr 2012 00:48:34 -0700
schrieb Walter Bright <newshou...@digitalmars.com>:

> On 4/6/2012 12:35 AM, Alex Rønne Petersen wrote:
> > It actually can be a problem. In .NET land, there are many
> > attributes across many projects (and even in the framework itself)
> > with the same names. It turns out that regular namespace lookup
> > rules alleviate this problem.
> 
> 
> Perhaps a better scheme is:
> 
>     enum foo = 3;
> 
>     ...
> 
>     @attr(foo) int x;
> 
> That way, foo will follow all the usual rules.
> 

The last time custom attributes where discussed, a C# like model was
proposed. Is there a good reason why we should deviate from the C#
implementation?

C#:
http://msdn.microsoft.com/en-US/library/48zeb25s(v=vs.80).aspx
http://msdn.microsoft.com/en-US/library/sw480ze8(v=vs.100).aspx
http://msdn.microsoft.com/en-US/library/z919e8tw(v=vs.80).aspx

(C# attributes can be applied to almost everything, therefore sometimes
 "disambiguating targets" is necessary. Probably not needed in D):
http://msdn.microsoft.com/en-US/library/b3787ac0(v=vs.80).aspx

Syntax in D would be different of course, but I see absolutely no need
for the redundant (and ugly) @attr.

Declaring a custom attribute:
---------
module std.something;

struct Author
{
    string name;
    public this(string name)
    {
        this.name = name;
    }
}
---------

Using it:
---------
import std.something; //Usual namespace lookup rules apply to attributes

/*
 * @Author(param) calls the constructor of the Author struct and
 * attaches the struct instance to test. Probably @Author (without
 * parenthesis) coud be made to mean std.something.Author.init 
 */
@Author("Johannes Pfau") int test;
---------

Attaching attributes multiple times as in C# should be possible.

Using reflection to get that attribute:
---------
if(__traits(hasAttribute, test, std.something.Author))
{
    Author[] authors = __traits(getAttribute, test,
        std.something.Author);
}
---------

An array is used here to support attaching the same attribute multiple
times. Of course "auto authors = ..." should be usable here too.

Reply via email to