繁体   English   中英

访问不在基本接口上的方法

[英]Accessing a method which is not on the base Interface

我有一个设计问题,正在寻找最好的设计解决方案。 我在下面添加了一个问题的示例。

public interface IVehicle<T>
{
    int GetEngineSize();
}

public class Car : IVehicle<Car>
{
    public int GetEngineSize()
    {
        throw new NotImplementedException();
    }

    public bool HasSpolier()
    {
        return true;
    }
}

public class Bus : IVehicle<Bus>
{
    public int GetEngineSize()
    {
        throw new NotImplementedException();
    }
}

public abstract class BaseController<T>
{
    public IVehicle<T> Repository { get; set; }
}

public abstract class CarController : BaseController<Car>
{
    public CarController()
    {
        // How can I access the HasSpolier method from the IVehicle<T> without having to cast the Interface to concrete class Car
        bool result = Repository.HasSpolier();
    }
}

我不确定你的仿制药在这里做了你想要的东西。

如果不是

IVehicle<T> Repository {get; set;}

你做到了

T Repository {get; set;}

你可以做

public abstract class BaseController<T> where T : IVehicle

确保它们是IVehicle接口

然后你就有了一个类型化的存储库并可以访问你的剧透方法。

你正在做IVehicle<Bus>但至少在示例代码中,T从未在接口中使用过。 在这一点上,T是毫无价值的。

除非您在界面中实现该方法,否则无法在不将其强制转换为其他类的情况下访问它。

您必须将您的存储库转换为Car。

它会使您的界面毫无意义,因为重新引入了您尝试删除的实现依赖性。

您的界面上的类型参数也不是必需的,您不要在界面的任何其他位置使用它...

public interface IVehicle
{
    int GetEngineSize();
}

暂无
暂无

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

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