在派生类中重写customattribute重写、类中、customattribute

2023-09-03 16:17:43 作者:最終的荒唐-

我们有一个自定义属性

[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
public class CustomDesignerAttribute: Attribute

那么,我们有装饰着这个属性的基类

then we have a base class decorated with this attribute

[CustomDesigner(someKey, someValue)]
public class BaseClass

那么我们就从这个派生的类,装饰着相同的属性(有相同的密钥,不同的值)

then we have a class derived from this one, decorated with same attribute (with same key, different value)

[CustomDesigner(someKey, someOtherValue)]
public class ChildClass : BaseClass

是否有ChildClass不创建属性的重复,但会覆盖现有的密钥,而不是值的可能性(覆盖整个parent属性)? 如果没有,什么是获取从BaseClass的默认值,如果ChildClass还没有确定最佳图案自己?

Is there possibility that ChildClass don't create a duplicate of attribute but overwrite a value for existing key instead (overwrites whole parent attribute)? If not, what's the best pattern for getting default value from BaseClass if ChildClass has not defined his own?

推荐答案

没有,这是不可能覆盖现有的属性。

No, it's not possible to override the existing attribute.

属性是附加到一个对象(组件,类,方法,变量等)的元数据,使他们始终保持这种的连接的。

Attributes are metadata attached to an object (assembly, class, method, variable and so on) so they always keep this connection.

如果你想在基类中提供一个默认的行为,并覆盖它的一些派生类,你必须检查所有通过返回的属性GetCustomAttributes()来只使用最衍生的一种(第一个列表中的)。

If you want to give a default "behavior" in the base class and override it in some derived classes you have to check all the attributes returned by GetCustomAttributes() to use only the most derived one (the first in the list).