c# - Attribute-Class, System.Attribute, Complex-Type -


it possible declare attributeclass filed , constructor of complex type?

the answer is: no! see post: https://stackoverflow.com/a/38509077/2935383

scroll down other solution.

my try:

own attribute-class

class attr : system.attribute {     private string _author;     private a[] _additionalparam;      public string author{ { return _author; } }     public a[] add{ { 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"), not constant.

edit: constructor take complex type ;)


my solution:

i've defined second attribute-class , set 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 attr-class

[attributeusage(attributetargets.class, allowmultiple = false, inherited = false)] class attr : system.attribute {     private string _author;      public string author{ { return _author; } }      public attr( string author ){         _author = author;     } } 

usage:

[attr("me ;)"] [additionlattr("a","b")] [additionlattr("c","d")] testclass{  } 

no, can't this. section 17.1.3 of c# language specification 5.0:

the types of positional , named parameters attribute class limited attribute parameter types are:

  • one of 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 above

a constructor argument or public field not have 1 of these types, cannot used positional or named parameter in attribute specification.


Comments