Limit the use of attributes to be mutually exclusive at design time?

I am developing a serialization class that uses attributes in custom classes to decorate whether a property is a fixed-length format or a delimiter format. These two attributes must be mutually exclusive, which means that the developer can either specify [FixedLength] or [Delimited] (with the corresponding constructors) properties, but not both. To reduce complexity and increase purity, I do not want to combine attributes and set a flag based on the type of format, for example. [Formatted(Formatter=Formatting.Delimited)] . Can these attributes be mutually exclusive at design time? I know how I can check this scenerio at runtime.

+6
source share
1 answer

You cannot do this in .NET. At best, you can allow one instance of the same attribute for a class, as in this example:

 using System; [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] class BaseAttribute : Attribute { } [Base] [Base] // compiler error here class DoubleBase { } 

But this behavior cannot be extended to derived classes, i.e. if you do this, it compiles:

 using System; [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] class BaseAttribute : Attribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] class Derived1Attribute : BaseAttribute { } [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] class Derived2Attribute : BaseAttribute { } [Derived1] [Derived2] // this one is ok class DoubleDerived { } 

The best I can think of is that you can write something to check for types with both attributes and use validation as a step after assembly.

+3
source

Source: https://habr.com/ru/post/901221/


All Articles