我想问高手一个问题,C#类的特性(如[STAThread()])。我如果继承了这个类,请问这个特性会被继承下去吗?

解决方案 »

  1.   

    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。