Skip to main content
 首页 » 编程设计

c#之访问不在基础接口(interface)上的方法

2024年02月23日22del

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

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接口(interface)

然后您将拥有一个类型化的存储库并可以访问您的剧透方法。

你正在做 IVehicle<Bus>但至少在示例代码中,界面中从未使用过 T。此时 T 毫无值(value)。