带有子类的c#继承重写方法参数

本文关键字:重写 方法 参数 继承 子类 | 更新日期: 2023-09-27 18:22:09

我试图概括这个问题,这样它仍然有意义,但还没有我实际类的所有代码。基本上,我想做的是让派生类中的方法覆盖它的祖先方法之一,但使用从祖先方法签名中的参数类派生的参数。希望这段代码能更好地解释它:

public abstract class BaseShape
{
    public int Id { get; set; }
    public bool Active { get; set; }
    public abstract bool Modified();
    public abstract void Validate(List<string> errors);
}
public class DescendantShape : BaseShape
{
    public int AnotherProperty { get; set; }
    public override bool Modified()
    {
        return true;
    }
    public override void Validate(List<string> errors)
    {
        //
    }
}
public abstract class BaseVehicle
{
    public void SaveChanges(BaseShape shape)
    {
        if (!shape.Modified()) return;
        var errorList = new List<string>();
        shape.Validate(errorList);
        if (errorList.Count > 0)
        {
            var sb = new StringBuilder();
            foreach (string s in errorList)
            {
                sb.Append(s + Environment.NewLine);
            }
            throw new Exception(sb.ToString());
        }
        WriteToStorage(shape);
        if (!shape.Active)
            MarkInactive(ref shape);
    }
    public abstract void WriteToStorage(BaseShape shape);
    public abstract void MarkInactive(ref BaseShape shape);
}
public class DescendantVehicle : BaseVehicle
{
    public override void WriteToStorage(DescendantShape shape)
    {
        //
    }
    public override void MarkInactive(ref DescendantShape shape)
    {
        shape = null;
    }
}

我不想为BaseVehicle的所有后代重复SaveChanges方法中的代码;但是,BaseVehicle的所有子体都将使用BaseShape的不同子体。当然,上面的代码不会构建,虽然我理解为什么(或者至少认为我理解),但我整个上午都在挠头,试图找出如何正确设计它。

带有子类的c#继承重写方法参数

您可以通过更新您的车辆类别来完成您想要的:

public abstract class BaseVehicle<T> where T : BaseShape
{
    public void SaveChanges(T shape)
    {
        if (!shape.Modified()) return;
        var errorList = new List<string>();
        shape.Validate(errorList);
        if (errorList.Count > 0)
        {
            var sb = new StringBuilder();
            foreach (string s in errorList)
            {
                sb.Append(s + Environment.NewLine);
            }
            throw new Exception(sb.ToString());
        }
        WriteToStorage(shape);
        if (!shape.Active)
            MarkInactive(ref shape);
    }
    public abstract void WriteToStorage(T shape);
    public abstract void MarkInactive(ref T shape);
}
public class DescendantVehicle : BaseVehicle<DescendantShape>
{
    public override void WriteToStorage(DescendantShape shape)
    {
        //
    }
    public override void MarkInactive(ref DescendantShape shape)
    {
        shape = null;
    }
}

这是Jon Skeet提到的实现泛型的解决方案。