2016-03-08 102 views
0

我想要在使用泛型的接口中實現這些方法。但我得到錯誤。 例如 // Filter是這裏的一個類。使用泛型實現多接口

public interface IComponent<T> 
{ 
    List<T> GetOrderSummary(Filter input); 
    T GetOrderDetails(string orderId); 
    List<T> GetOrderSummaryDetails(Filter input); 
} 

// ORDER A AND ORDER B ARE TWO MODEL CLASSES HERE 
public class OrderDetails : IComponent<OrderA>,IComponent<OrderB> 
{ 
    public List<OrderA> GetOrderSummary(Filter input) 
    { 
    //Some logic 
    //lst of type OrderA 
    return lst; 
    } 

    public List<OrderB> GetOrderSummaryDetails(Filter input) 
    { 
    //Some logic 
    //lst of type OrderB 
    return lst 
    } 

    public OrderA GetOrderDetails(string orderId) 
    { 
    throw new NotImplementedException(); 
    } 
} 

我得到錯誤的建築,

訂單明細沒有實現接口成員IComponent.GetOrderSummaryDetails(過濾器).OrderDetails.GetOrderSummaryDetails無法實現IComponent.GetOrderSummaryDetails(過濾器)怎麼一回事,因爲它不具有匹配的List<OrderA>

訂單明細返回類型未實現接口構件IComponent.GetOrderSummary(濾波器).OrderDetails.GetOrderSummary不能怎麼一回事,因爲它實現IComponent.GetOrderSummary(過濾器)不具有的List<OrderB>

訂單明細匹配的返回類型未實現接口構件IComponent.GetOrderDetails(字符串).OrderDetails.GetOrderDetails(字符串)不能實現IComponent.GetOrderDetails(字符串)東陽它不具有匹配返回類型OrderB

請讓我知道如何解決這些問題。

+0

您是否嘗試過使用顯式接口實施? afaik方法僅通過它們的名稱和輸入參數來區分,而不是它們的返回值。 – Domysee

+1

'OrderDetails'類是否僅包含3個方法?請注意,你不能隱式地實現這兩個接口,因爲那麼你將有兩個具有相同參數但返回值類型不同的方法,這在c#中是非法的。你可以明確地實現它們。 –

回答

1

你需要顯式實現兩個接口的,就像這樣:

public class OrderDetails : IComponent<OrderA>, IComponent<OrderB> 
{ 
    List<OrderA> IComponent<OrderA>.GetOrderSummary(Filter input) 
    { 
     throw new NotImplementedException(); 
    } 

    OrderB IComponent<OrderB>.GetOrderDetails(string orderId) 
    { 
     throw new NotImplementedException(); 
    } 

    List<OrderB> IComponent<OrderB>.GetOrderSummaryDetails(Filter input) 
    { 
     throw new NotImplementedException(); 
    } 

    List<OrderB> IComponent<OrderB>.GetOrderSummary(Filter input) 
    { 
     throw new NotImplementedException(); 
    } 

    OrderA IComponent<OrderA>.GetOrderDetails(string orderId) 
    { 
     throw new NotImplementedException(); 
    } 

    List<OrderA> IComponent<OrderA>.GetOrderSummaryDetails(Filter input) 
    { 
     throw new NotImplementedException(); 
    } 
} 

後來,訪問您可以使用鑄造或正確的變量類型正確方法:

var orderDetails1 = new OrderDetails(); 
var details1 = ((IComponent<OrderA>)orderDetails1).GetOrderDetails(""); 

IComponent<OrderA> orderDetails2 = new OrderDetails(); 
var details2 = orderDetails2.GetOrderDetails("");