2013-04-22 84 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 
} 
相关问题