簡體   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