How does inheritance work for Attributes?(继承如何对属性起作用?)
问题描述
属性上的 Inherited
bool 属性指的是什么?
What does the Inherited
bool property on attributes refers to?
这是否意味着如果我使用属性 AbcAtribute
(具有 Inherited = 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?
为了用一个代码示例来澄清这个问题,想象一下:
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
{ }
Child
是否也应用了 Random
属性?
Does Child
also have the Random
attribute applied to it?
推荐答案
当Inherited = true(默认)时,表示你创建的属性可以被该属性修饰的类的子类继承.
When Inherited = true (which is the default) it means that the attribute you are creating can be inherited by sub-classes of the class decorated by the attribute.
所以 - 如果您使用 [AttributeUsage (Inherited = true)] 创建 MyUberAttribute
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,其中Bob"作为 SpecialName 值.
MySubClassInstance <--- now has the MyUberAttribute with "Bob" as the SpecialName value.
这篇关于继承如何对属性起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:继承如何对属性起作用?


- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 使用 rss + c# 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01