如何为类型的字段设置固定值
本文关键字:设置 字段 类型 | 更新日期: 2023-09-27 18:04:08
如果我有这样的类层次结构:
Class Shape
{
public bool closedPath;
}
class Circle : Shape
{
}
class Line: Shape
{
}
这里我知道所有的圆都是闭合路径。如何将closedPath
字段的值设置为这些默认值,而不需要在实例化该类的对象时分配其值?
您可以将closepath声明为虚拟只读属性,然后在后代类中定义它:
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接口
你也可以用一个只读字段来实现相同的结果,并在构造函数中初始化该字段。
可以将值传递给基类构造函数:
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
}