如何进行属性继承的工作? [英] How does inheritance work for Attributes?
问题描述
什么的继承
布尔的属性属性是指?
What does the Inherited
bool property on attributes refers to?
这是否意味着,如果我有一个属性 AbcAtribute
定义我的类(即具有继承= TRUE
),如果我继承另一个类从该类,该派生类也将有相同的属性应用到它?
Does it mean that if I define my class with an attribute AbcAtribute
(that has Inherited = true
), and if I inherit another class from that class, that the derived class will also have that same attribute applied to it?
要澄清这个问题有code例如,想象一下以下内容:
To clarify this question with a code example, imagine the following:
[AttributeUsage(AttributeTargets.Class, Inherited = true)]
public class Random: Attribute
{ /* attribute logic here */ }
[Random]
class Mother
{ }
class Child : Mother
{ }
确实孩子
也有随机
属性应用到它?
Does Child
also have the Random
attribute applied to it?
推荐答案
在继承= TRUE这意味着你创建的属性可以通过子类的类的属性装饰的继承。
When Inherited = true it means that the attribute you are creating can be inherited by sub-classes of the class decorated by the attribute.
所以 - 如果你创建MyUberAttribute使用[AttributeUsage(继承= TRUE)]
So - if you create MyUberAttribute with [AttributeUsage (Inherited = true)]
[AttributeUsage (Inherited = True)]
MyUberAttribute : Attribute
{
string _SpecialName;
public string SpecialName
{
get { return _SpecialName; }
set { _SpecialName = value; }
}
}
然后,通过装饰超一流的使用属性...
Then use the Attribute by decorating a super-class...
[MyUberAttribute(SpecialName = "Bob")]
class MySuperClass
{
public void DoInterestingStuf () { ... }
}
如果我们创建一个子类MySuperClass它都会有这样的属性...
If we create an sub-class of MySuperClass it will have this attribute...
class MySubClass : MySuperClass
{
...
}
然后实例MySubClass ...
Then instantiate an instance of MySubClass...
MySubClass MySubClassInstance = new MySubClass();
然后进行测试,看它是否具有属性...
Then test to see if it has the attribute...
MySubClassInstance< ---现在有MyUberAttribute与鲍勃作为SpecialName值
MySubClassInstance <--- now has the MyUberAttribute with "Bob" as the SpecialName value.
这篇关于如何进行属性继承的工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!