在派生类中重写customattribute [英] Overwrite customattribute on derived class

查看:138
本文介绍了在派生类中重写customattribute的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个自定义属性

[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).

这篇关于在派生类中重写customattribute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆