【问题标题】:Interface method that receives a parameter of type of class that inherited it接收继承它的类类型参数的接口方法
【发布时间】:2023-03-26 14:45:01
【问题描述】:

我正在尝试做这样的事情:

public interface ICar
{
    public void Update(/*something here*/);
}

然后是两个类:

public class Peugeot : ICar
{
    public void Update(Peugeot car)
    {

    }
}

public class Volvo : ICar
{
    public void Update(Volvo car)
    {

    }
}

我怎样才能做到这一点?

【问题讨论】:

  • OP 可能希望将每个实现限制为只接受自己的类型,尽管他忘了提及。
  • Update 方法如何处理它的参数?
  • 正如@boli 所问,这样做有什么意义? car 参数与处理它的实际实例(this 实例,如果你愿意的话)有何不同?

标签: c# class methods interface


【解决方案1】:

您可以将ICar 设为通用:

public interface ICar<T> where T : ICar<T>
{
    public void Update<T>(T car);
}

然后相应地实现Update方法:

public class Peugeot : ICar<Peugeot>
{
    public void Update(Peugeot car)
    {

    }
}

public class Volvo : ICar<Volvo>
{
    public void Update(Volvo car)
    {

    }
}

【讨论】:

【解决方案2】:

您可以(至少在某种程度上)通过明确的接口实现来实现这一点,然后提供一个正确类型的公共Update 方法:

public interface ICar
{
    void Update(ICar car);
}

public class Peugeot : ICar
{
    public void Update(Peugeot car)
    {
        Update(car);
    }

    void ICar.Update(ICar car)
    {
        // do some updating
    }
}

public class Volvo : ICar
{
    public void Update(Volvo car)
    {
        Update(car);
    }

    void ICar.Update(ICar car)
    {
        // do some updating
    }
}

【讨论】:

  • 如果 ICar.Update 将在一个通用接口上完成所有工作,我认为没有一个特定于该派生类型的单独方法的意义。
  • @Groo 它会阻止你编写像new Volvo().Update(new Peugeot()); 这样的代码,只有常规接口实现才允许。你仍然可以写((ICar)new Volvo()).Update(new Peugeot());,但这样更难弄错。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-06
  • 2022-01-04
  • 1970-01-01
  • 2013-02-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多