[英]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.