繁体   English   中英

具有后代类的C#继承重写方法参数

[英]c# inheritance override method parameter with a descendant class

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

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的differentnet后代。 上面的代码当然不会生成,虽然我理解为什么(或者至少认为是这样),但整个上午我一直在努力寻找方法,以弄清楚如何正确设计它。

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

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提到的泛型的解决方案。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM