Interface method that receives a parameter of type of class that inherited it

北战南征 提交于 2021-02-11 15:45:54

问题


I' trying to make something like this:

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

Then two classes:

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

    }
}

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

    }
}

How can I achieve this?


回答1:


You could make ICar generic:

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

And then implement the Update methods accordingly:

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

    }
}

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

    }
}



回答2:


You can (at least sort of) achieve this by making an explicit interface implementation, and then providing a public Update method that is properly typed:

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
    }
}


来源:https://stackoverflow.com/questions/21186347/interface-method-that-receives-a-parameter-of-type-of-class-that-inherited-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!