【问题标题】: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;
}
您还可以考虑:
【解决方案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
}