C#的特性在继承类中不会被继承吗?

美福种田伯 2009-03-04 03:48:55
我想问高手一个问题,C#类的特性(如[STAThread()])。我如果继承了这个类,请问这个特性会被继承下去吗?
...全文
809 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
美福种田伯 2009-03-04
  • 打赏
  • 举报
回复
这位兄台说的非常对!非常感谢

[Quote=引用 1 楼 zwicker 的回复:]
Ok,现在我们来讨论一下最后的这个属性。Inherited, 表明当特性被放置在一个基类上时,它能否被派生类所继承。

[Help("BaseClass")] publicclass Base{} publicclass Derive : Base{}
这里会有四种可能的组合:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false ]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false ]
[AttributeUsage(Attrib…
[/Quote]
Grave_rain 2009-03-04
  • 打赏
  • 举报
回复
继承嗨没学好,学好了想想!!
zwicker 2009-03-04
  • 打赏
  • 举报
回复
Ok,现在我们来讨论一下最后的这个属性。Inherited, 表明当特性被放置在一个基类上时,它能否被派生类所继承。

[Help("BaseClass")] publicclass Base{} publicclass Derive : Base{}
这里会有四种可能的组合:

[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = false ]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false ]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true ]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = true ]
第一种情况:

如果我们查询(Query)(稍后我们会看到如何在运行期查询一个类的特性)Derive类,我们将会发现Help特性并不存在,因为inherited属性被设置为false。

第二种情况:

和第一种情况相同,因为inherited也被设置为false。



第三种情况:

为了解释第三种和第四种情况,我们先来给派生类添加点代码:

[Help("BaseClass")] publicclass Base{}[Help("DeriveClass")] publicclass Derive : Base{}
现在我们来查询一下Help特性,我们只能得到派生类的属性,因为inherited被设置为true,但是AllowMultiple却被设置为false。因此基类的Help特性被派生类Help特性覆盖了。

第四种情况:

在这里,我们将会发现派生类既有基类的Help特性,也有自己的Help特性,因为AllowMultiple被设置为true。

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧