简体   繁体   中英

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

if i have this code:

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

is there anything that support doing something like this:

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

so it will accept anything that supports one of two interfaces. I am basically trying to create an overload.

As far as I know, you can use AND logic not OR .

AND (in this case, T must be child of IFilterable and ISemiFilterable )

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

不,语言不支持。

The easy way I would say, is if both your interfaces where children of the same parent interface.

public interface IFilterable { }

public interface IFullyFilterable : IFilterable { }

public interface ISemiFilterable : IFilterable { }

... where T : IFilterable { }

The language doesn't support 'oring' together interfaces/classes in the where clause.

You need will need to state them separately with different method names so the signatures are different.

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

Alternatively you can implement a common interface on both interfaces. This is not the same thing as above though as it may require a cast when you receive the object back if you need a specific interface that isn't contained within 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
}

I don't know the context but the above is probably what you're looking for.

You can just add another empty base interface that both these interfaces are derived from...

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

and then demand that the type in the generic type constraint be the base interface

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

The only downside is the compiler will not allow you to use methods from either of the derived interfaces without casting...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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