在设计时将属性使用限制为互斥?

Geo*_*ton 6 c# attributes

我正在开发一个序列化类,它使用自定义类的属性来修饰属性是固定长度格式还是分隔格式.这两个属性应该是互斥的,这意味着开发人员可以在属性上指定[FixedLength][Delimited](使用适当的构造函数),但不能同时指定两者.为了降低复杂性,提高洁净度,我想要的属性结合起来,并设置基于格式类型的标志,例如[Formatted(Formatter=Formatting.Delimited)].是否可以在设计时将这些属性限制为彼此互斥?我知道如何在运行时检查这个场景.

Pao*_*sco 3

您无法在 .NET 中执行此操作。最多可以在类上允许相同属性的单个实例,如下例所示:

using System;

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
class BaseAttribute : Attribute {
}

[Base]
[Base] // compiler error here
class DoubleBase { 
}
Run Code Online (Sandbox Code Playgroud)

但是这种行为不能扩展到派生类,即如果你这样做它会编译:

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 {
}
Run Code Online (Sandbox Code Playgroud)

我能想到的最好的办法是,您可以编写一些内容来检查是否没有应用这两个属性的类型,并将该检查用作构建后步骤。