在C#中查找调用Parent Property的子级



我正在尝试解决C#(MS Visual Studio(中的一些作业,如果能得到一些指导,我将不胜感激。我会";转述";逻辑如下:

class Vehicle
{
public int Property{get {return Fuel}
set{ if TwoWheeler child called property then set max = 10
else(other alternate is FourWheeler child)  max = 50}
}
class TwoWheeler : Vehicle
{ }
class FourWheeler : Vehicle
{}
class Program
{
TwoWheeler TwoWheeler_object = new TwoWheeler();
FourWheeler FourWheeler_object = new FourWheeler();
CW(TwoWheeler_object.Property);
CW(FourWheeler_object.Property);
}

这是代码的基本骨架版本。如果需要任何澄清,我们很乐意这样做。感谢您提前提供的帮助。

编辑

如果TwoWheeler调用Property,则设置Property,maxLimit=10,如果给定的Fuel小于maxLimit,则设置Fuel=值,如果Fuel大于或等于maxLimit,那么设置Fuel=maxLimit

如果FourWheeler从车辆调用Property,则maxLimit=50,则其余部分为相同的

如果我理解正确;max";值取决于调用代码的子类。

如果有一种模式,特别是对于那种被称为";模板图案":

public abstract class Vehicle
{
protected abstract int MaxValue { get; }
private int _myField;
public int MyProperty
{
get => _myField;
set
{
if (value <= MaxValue)
{
_myField = value;
}
}
}
}
public class TwoWheeler : Vehicle
{
protected override int MaxValue => 10;
}
public class FourWheeler : Vehicle
{
protected override int MaxValue => 50;
}

我使Vehicle类成为抽象类,因为在代码中,您总是需要它是FourWheelerTwoWheeler,这意味着它永远不应该是简单的Vehicle

车辆包含您想要应用的逻辑:检查是否未达到最大值(很明显,您可以放置else并显示异常,在这种情况下,我只是选择不分配任何内容(。

然后,子级必须重写MaxValue(因为它是抽象的(,并且该值将由父级使用。

它有一些优点:

  • 逻辑不重复
  • 家长不了解孩子
  • 添加新的子项而不提供此值将导致编译中断

如果我理解正确的话您可以将此逻辑放入父类的集合中:

public int Property{get {return Fuel}
set
{ 
switch(this.GetType().Name)
{
case typof(TwoWheeler).Name:
max = 10;
break;
case typof(FourWheeler).Name:
max = 50
break;
}
}

相关内容

最新更新