Attribute Class, System.Attribute, Complex Type

It is possible do declare a AttributeClass with a filed and constructor of complex type?

The answer is: No! see this post: https://stackoverflow.com/a/38509077/2935383

Scroll down for a other solution.

My try:

Own attribute-class

class Attr : System.Attribute {
    private string _author;
    private A[] _additionalParam;

    public string Author{ get { return _author; } }
    public A[] Add{ get { return _additionalParam; } }

    public Attr( string author, params A[] add ){
        _author = author;
        _additionalParam = add;
    }
}

Complex type

class A{
    public string abc;
    public string def;

    public A( string a, string b ){
        abc = a;
        def = b;
    }
}

Usage attribute class

//this dosn't work
[Attr("me ;)", new A("a","b"), new A("c", "d")] 
TestClass{

}

Cannot use new A("a","b"), it is not constant.

Edit: constructor also take the complex type ;)


My solution:

I've defined a second Attribute-Class and set it to multiple.

[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
class AdditionlAttr : System.Attribute
    public string abc;
    public string def;

    public AdditionlAttr( string a, string b ){
        abc = a;
        def = b;
    }
}

And change the Attr-Class

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false)]
class Attr : System.Attribute {
    private string _author;

    public string Author{ get { return _author; } }

    public Attr( string author ){
        _author = author;
    }
}

Usage:

[Attr("me ;)"]
[AdditionlAttr("a","b")]
[AdditionlAttr("c","d")]
TestClass{

}
Jon Skeet
people
quotationmark

No, you can't do this. From section 17.1.3 of the C# Language Specification 5.0:

The types of positional and named parameters for an attribute class are limited to the attribute parameter types which are:

  • One of the following types: bool, byte, char, double, float, int, long, sbyte, short, string, uint, ulong, ushort
  • The type object
  • The type System.Type
  • An enum type [...]
  • Single-dimensional arrays of the above

A constructor argument or public field which does not have one of these types, cannot be used as a positional or named parameter in an attribute specification.

people

See more on this question at Stackoverflow