【问题标题】:Are Method Attributes Inherited in C#?方法属性是否在 C# 中继承?
【发布时间】:2010-11-10 13:09:39
【问题描述】:

应用于基类中的抽象方法的属性是否应用于子类中的覆盖版本?

我希望这个问题没有例子就足够清楚了。

【问题讨论】:

    标签: c# inheritance attributes methods


    【解决方案1】:

    这取决于属性本身的声明方式 - 请参阅 AttributeUsageAttribute.Inherited 属性。

    【讨论】:

      【解决方案2】:

      这取决于属性。

      应用于 Attribute 类定义的属性,带有一个属性 [AttributeUsageAttribute.Inherited],用于确定某个属性是否在派生类中被继承。

      查看此示例

      [global::System.AttributeUsage(AttributeTargets.Method, Inherited = true, 
           AllowMultiple = false)]
      public sealed class MyAttribute : Attribute
      {
      
          public MyAttribute (string FieldName)
          {
              //constructor.
          }
      
      }
      

      【讨论】:

        【解决方案3】:

        您可以通过将AttributeUsage attribute 应用于您的自定义,并设置Inherited property(默认情况下为真)来指定。此属性指示您的属性是否可以被从应用了您的自定义属性的类派生的类继承。

        [AttributeUsage( Inherited = false)]
        public class CustomAttribute : Attribute
        {
        }
        

        推荐阅读:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-05-08
          • 2016-11-13
          • 2018-09-09
          • 2017-12-18
          • 1970-01-01
          • 2021-02-15
          • 2022-07-27
          • 1970-01-01
          相关资源
          最近更新 更多