【问题标题】:How to set a fixed value to fields to a type?如何将字段的固定值设置为类型?
【发布时间】:2016-08-25 23:36:38
【问题描述】:

如果我有这样的类层次结构:

Class Shape
{
public bool closedPath;
}

class Circle : Shape
{
}
class Line: Shape
{
}

在这里我知道所有的圈子都是封闭的路径。 如何在实例化该类的对象时将closedPath 字段的值设置为这些默认值而无需分配其值?

【问题讨论】:

    标签: c# oop inheritance polymorphism


    【解决方案1】:

    您可以将您的 closedPath 声明为虚拟只读属性,然后在后代类中定义它:

    class Shape
    {
        public virtual bool closedPath {get;}
    }
    
    class Circle : Shape
    {
        public override bool closedPath => true;
    }
    class Line: Shape
    {
        public override bool closedPath => false;
    }
    

    您还可以考虑:

    • 将 Shape 类更改为抽象类或 IShape 接口。

    • 您也可以使用只读字段实现相同的结果,并在构造函数中初始化该字段。

    【讨论】:

      【解决方案2】:

      您可以将值传递给基本构造函数:

      class Shape
      {
          public bool closedPath;
      
          public Shape(bool closedPath)
          {
              this.closedPath = closedPath;
          }
      }
      
      class Circle : Shape
      {
          public Circle()
              : base(true)
          {
          }
      }
      
      class Line : Shape
      {
          public Line()
              : base(false)
          {
          }
      }
      

      然后你会得到:

      void SomeMethod()
      {
          Shape circle = new Circle();
          Console.WriteLine(circle.closedPath);  // True
      
          Shape line = new Line();
          Console.WriteLine(line.closedPath);  // False
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-09-14
        • 2022-09-24
        • 1970-01-01
        • 2021-08-23
        • 2019-09-25
        • 2022-09-28
        相关资源
        最近更新 更多