假设我有一个抽象基类,Shape,然后是三个派生类:Triangle,Rectangle和Pentagon.必须根据需求创建派生类,这样我就可以拥有每个派生类中的几个.基类有很多字段,我一直在寻找一种方法只设置一次基类属性,然后稍后为派生类设置不同的字段.既然你无法实例化一个抽象类,那么最好的方法是什么?我想也许创建另一个派生自Shape的类,它只具有Shape的属性,设置那些属性然后转换它但这看起来效率低下并且在它上面写了代码味道.有人可以提出更好的方法吗?谢谢.下面我写了一些针对这种情况的伪代码
public abstract class Shape
{
public int x, y, z;
}
public class Triangle : Shape
{
public int a, b, c
}
public class Facade : Shape
{
}
private Facade InitializeBaseProperties()
{
Facade f = new Training
{
x = 1, y = 2, z = 3
};
return f;
}
private void someMethod()
{
var tmp = InitializeBaseProperties();
Triangle triangle = tmp;
}
Run Code Online (Sandbox Code Playgroud)
确实,您无法实例化抽象类,但这并不意味着抽象类不能具有构造函数.
在抽象类中使用构造函数并将其链接到具体的实现类构造函数:
public abstract class Shape
{
protected int _x, _y, _z;
protected Shape(int x, int y, int z)
{
_x = x;
_y = y;
_z = z;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,在派生类中:
public class Triangle : Shape
{
public Triangle (int x, int y, int z, int a, int b) : base(x,y,z)
{
A = a;
B = b;
}
public int A {get;}
public int B {get;}
}
Run Code Online (Sandbox Code Playgroud)