【问题标题】:Complete nested partial class in child class在子类中完成嵌套部分类
【发布时间】:2017-03-14 19:23:46
【问题描述】:

我有两个类,A 和 B。B 继承自 A。

这是我的问题:我有一个常量 ConstantA,它对 A 类有用,但对子类也有用。我还有一个常量 ConstantB,它是特定于我的 B 类的。

由于我将常量存储在公共静态嵌套类中,因此子类中的常量类隐藏了父类。我尝试将其设为部分课程,但无济于事。有没有办法解决这个问题?

这是一个例子:

public class A 
{
    public static partial class Constants
    {
        public const int ConstantA = 1;
    }
}

public class B : A 
{
    public static partial class Constants
    {
        public const int ConstantB = 1;
    }
}

谢谢!

【问题讨论】:

  • 如果ConstantA 对所有子类都有用,为什么不将其移到父类而不是内部静态类中?

标签: c# inner-classes partial-classes


【解决方案1】:

您还需要将 A 设为部分类,并将 B 特定常量与 B 类本身分开声明:

public partial class A
{
    public static partial class Constants
    {
        public const int ConstantA = 1;
    }
}

public partial class A
{
    public static partial class Constants
    {
        public const int ConstantB = 1;
    }
}

public class B : A
{
    static void M()
    {
        int i = Constants.ConstantB;
        int j = Constants.ConstantA;
    }
}

也就是说,我怀疑设计是否有那么好。它具有在A 中声明ConstantB 值的效果,这似乎与封装的目标相反,假设ConstantB 确实只与类B 相关。如果您以这种方式声明它,ConstantB 可以通过 any 以任何类型使用 Constants 类访问。

但是,如果您对此没意见,并且只是想确保常量的 声明 保留在 B 类中,那么上述方法将起作用。

其他选项包括继续并隐藏(使用new 关键字)基类Constants,稍有不便之处在于必须将基类指定为完全限定的才能访问基值(例如A.Constants.ConstantA ),隐藏基类并让B.Constants 类继承A.Constants(需要放弃static 类属性)或者,恕我直言,根本不使用嵌套类,而是将Constants 类放入它们各自的命名空间。

【讨论】:

    【解决方案2】:

    只需将您的 ConstantA 设置为父类的属性,将此属性放在嵌套类中即可将其从继承类的范围中删除。

    【讨论】:

      【解决方案3】:

      如果你真的想要嵌套类,你可以留下static关键字,并为B.Constants嵌套类做继承:

      public class A 
      {
          public class Constants
          {
              public const int ConstantA = 1;
          }
      }
      
      public class B : A 
      {
          public new class Constants : A.Constants
          {
              public const int ConstantB = 2;
          }
      }
      

      用法相同。

      【讨论】:

        猜你喜欢
        • 2012-02-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-01-25
        • 2022-01-21
        • 2014-12-04
        • 2019-07-29
        • 1970-01-01
        相关资源
        最近更新 更多