2013-04-22 44 views
5

,如果我有這樣的代碼:在C#中,你可以把一個Or放在「where」接口約束中嗎?

public interface IJobHelper 
{ 
    List<T> FilterwithinOrg<T>(IEnumerable<T> entities) where T : IFilterable; 
} 

有什麼支持做這樣的事情:

public interface IJobHelper 
{ 
    List<T> FilterwithinOrg<T>(IEnumerable<T> entities) where T : IFilterable or ISemiFilterable 
} 

所以它會接受任何支持的兩個接口之一。我基本上試圖創造一個超載。

+0

何不做一個通用的過濾類,那麼繼承類更具體可過濾的類。然後,您可以將where子句用於泛型可過濾類並將其約束爲多個類。 – 2013-04-22 03:36:29

+0

http://stackoverflow.com/questions/3679562/generic-methods-and-method-overloading – Turbot 2013-04-22 03:40:39

回答

2

該語言不支持將where子句中的接口/類「組合」在一起。

您需要用不同的方法名分別聲明它們,所以簽名是不同的。

public interface IJobHelper 
{ 
    List<T> FilterwithinOrg<T>(IEnumerable<T> entities) 
     where T : IFilterable 
    List<T> SemiFilterwithinOrg<T>(IEnumerable<T> entities) 
     where T : ISemiFilterable 
} 

或者,您可以在兩個接口上實現通用接口。這與上述內容不同,因爲如果您需要特定接口但不包含在IBaseFilterable中,則當您收到對象時可能需要進行強制轉換。

public interface IBaseFilterable { } 
public interface IFilterable : IBaseFilterable { } 
public interface ISemiFilterable : IBaseFilterable { } 

public interface IJobHelper 
{ 
    List<T> FilterwithinOrg<T>(IEnumerable<T> entities) 
     where T : IBaseFilterable 
} 

我不知道上下文,但上面可能是你要找的。

+0

我嘗試了第一件事,只是在不同的Where約束接口中列出了兩次,但我得到了「同樣的方法已經聲明」錯誤。 。有任何想法嗎? – leora 2013-04-22 03:42:47

+0

沒錯,我會解決答案。你需要給他們不同的名字 – 2013-04-22 03:49:27

2

我會說,簡單的方法是,如果你的界面在同一父界面的子項。

public interface IFilterable { } 

public interface IFullyFilterable : IFilterable { } 

public interface ISemiFilterable : IFilterable { } 

... where T : IFilterable { } 
+0

這不是** OR **邏輯。如果你有* ISemiFilterable *的子類,那麼表示這個類也是* IFilterable *的子類。 – 2013-04-22 04:12:58

+0

@VanoMaisuradze是嗎?結果會是一樣的嗎? – LightStriker 2013-04-22 14:29:02

+0

哪個結果?你寫的是不是OR。這是AND – 2013-04-22 14:48:12

0

您可以再補充,這兩個接口都源於另一個空底座接口...

interface baseInterface {} 
interface IFilterable: baseInterface {} 
interface ISemiFilterable: baseInterface {} 

,然後要求在泛型類型約束類型是基本接口

List<T> FilterwithinOrg<T>(IEnumerable<T> entities) where T : baseInterface 

唯一的缺點是編譯器不允許你使用任何派生接口的方法而無需強制轉換...

3

據我所知,你可以使用邏輯不是

(在這種情況下,牛逼必須是孩子IFilterableISemiFilterable

public interface IJobHelper 
{ 
    List<T> FilterwithinOrg<T>(IEnumerable<T> entities) where T : IFilterable, ISemiFilterable 
} 
相關問題