Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create duplicate allowed attributes

Tags:

c#

attributes

I'm using a custom attribute inherited from an attribute class. I'm using it like this:

[MyCustomAttribute("CONTROL")] [MyCustomAttribute("ALT")] [MyCustomAttribute("SHIFT")] [MyCustomAttribute("D")] public void setColor() {  } 

But the "Duplicate 'MyCustomAttribute' attribute" error is shown.
How can I create a duplicate allowed attribute?

like image 210
ebattulga Avatar asked Feb 16 '09 14:02

ebattulga


People also ask

Can XML have duplicate attributes?

Duplicate attributes (on the same element) are not allowed in a well-formed XML document by definition.

What does duplicate attributes mean?

Duplicate attribute values are those where multiple features share the same value for the same attribute. In many cases this is natural and expected; for example, the province (county/state) field for an address database is very likely to be the same for many records.

What is AttributeUsage C#?

Determines how a custom attribute class can be used. AttributeUsage is an attribute that can be applied to custom attribute definitions to control how the new attribute can be applied. So it basically gives the compiler some extra information about the attribute class you will implement.


2 Answers

Stick an AttributeUsage attribute onto your Attribute class (yep, that's mouthful) and set AllowMultiple to true:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public sealed class MyCustomAttribute: Attribute 
like image 142
Anton Gogolev Avatar answered Sep 24 '22 11:09

Anton Gogolev


AttributeUsageAttribute ;-p

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class MyAttribute : Attribute {} 

Note, however, that if you are using ComponentModel (TypeDescriptor), it only supports one attribute instance (per attribute type) per member; raw reflection supports any number...

like image 35
Marc Gravell Avatar answered Sep 21 '22 11:09

Marc Gravell