[英]Generic interface with generic elements and constraints
我想定義一個包含泛型元素的泛型庫:
public interface ILibrary<T>
我的通用元素定義如下:
interface ILibElement<T, IVersion<T>>
我想添加一個約束,說庫中的元素必須實現ILibElement。 所以我想我可以像這樣更改ILibrary的定義:
public interface ILibrary<T> where T : ILibElement<T, IVersion<T>>
但是我必須添加類型參數。 所以我想做些類似的事情:
public interface ILibrary<ILibElement<T, IVersion<T>>>
但是T是不確定的。
我找不到正確的語法 。 我如何表達這樣的約束?
我相信您只是想這樣做:
where T : ILibElement<T, IVersion<T>>
因為ILibElement
表示為ILibElement<T, IVersion<T>>
您只需要使用要實現的T
專門實現該接口。
我認為您可以嘗試這樣的邏輯
public interface ILibrary<T,V> where T:ILiBelement<T,V> where T:ILiBelement<T,V>
where V:IVersion<V>
{
}
interface ILiBelement<T,V> where V:IVersion<T>
{
}
interface IVersion<T>
{
}
希望這個幫助
必須將通用類型參數指定為標識符; 約束可以使用更復雜的嵌套公式,但參數本身不能。 如果有人想要一種通用方法,該方法采用某種類型為Nullable<T>
的參數,則不會將其指定為:
void ThisWontWork<Nullable<T>>(T it) where T:struct {...}
但改為:
void ThisWillWork<T>(Nullable<T> it) where T:struct {...}
如果您的集合中可能包含具有所有類型的進一步限定的通用屬性,則您可能希望將該類型添加為集合的類型參數:
class ListOfLists<T,U> where T:IList<U>
如果您的集合中將包含實現具有各種泛型類型的泛型接口的事物,但是您只需要使用不涉及此類的成員,那么在可能的情況下,您應該擁有不關心該類型的成員。泛型類型被隔離到它們自己的接口中,該接口可以被完整的泛型繼承。 例如,盡管Microsoft並非以這種方式設計其IDictionary
,但它可以被定義為(部分:)
interface ICheckIfContained
{ bool Contains(object it); }
interface ICheckIfContained<in T> : ICheckIfContained
{ bool Contains(T it); }
interface IDictionary<in TKey, out TValue> : ICheckIfContained<TKey> ...
如果僅出於掃描鍵中的鍵的目的而僅希望保存字典參考的集合,而不考慮這些鍵將映射到的鍵,則約束到ICheckIfContained
的通用參數可以達到這一目的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.