繁体   English   中英

在C#中,你可以将Or放在“where”接口约束中吗?

[英]In C#, can you put an Or in an “where” interface constraint?

如果我有这个代码:

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
}

所以它会接受任何支持两个接口之一的东西。 我基本上试图创建一个重载。

据我所知,你可以使用AND逻辑而不是OR

AND (在这种情况下, T必须是IFilterable ISemiFilterable的子代

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

不,语言不支持。

我想说的简单方法是,如果你的接口都是同一个父接口的子接口。

public interface IFilterable { }

public interface IFullyFilterable : IFilterable { }

public interface ISemiFilterable : IFilterable { }

... where T : IFilterable { }

该语言不支持where子句中的“oring”接口/类。

您需要使用不同的方法名称分别说明它们,以便签名不同。

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

或者,您可以在两个接口上实现通用接口。 这与上面的内容不同,但如果您需要一个未包含在IBaseFilterable的特定接口,则在收到对象时可能需要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
}

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

您可以添加另一个空基本接口,这两个接口都派生自...

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

然后要求泛型类型约束中的类型是基接口

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

唯一的缺点是编译器不允许您使用来自任何派生接口的方法而不进行转换...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM