[英]Indexer constraint on generic types
是否可以創建一個類型必須具有索引器的泛型類/方法?
我的想法是讓以下兩種擴展方法適用於使用索引器獲取和設置值的任何類型,但似乎無法找到任何關於它的內容。 只有關於使索引器本身通用的東西,這不是我追求的......
public static T GetOrNew<T>(this HttpSessionStateBase session, string key) where T : new()
{
var value = (T) session[key];
return ReferenceEquals(value, null)
? session.Set(key, new T())
: value;
}
public static T Set<T>(this HttpSessionStateBase session, string key, T value)
{
session[key] = value;
return value;
}
無法應用泛型類型參數具有索引器(或任何運算符)的泛型約束。 您可以做的最好的事情是創建具有該限制的接口,並限制泛型參數以實現該接口。
Servy有它。 您不能要求該類型具有索引器,但您可以要求該類型實現公開索引器的接口。 IList
和IDictionary
及其通用對應物是主要的內置接口,它們分別使用整數和字符串索引值來公開索引器。 不幸的是,一些內置類型(如HttpSessionState)會自動公開索引器,而不會實現識別它們的接口。
您還可以定義自己的索引接口以應用於您控制的任何類型:
public interface IIndexable<TKey, TVal>
{
TVal this[TKey key]{get;}
}
所以,最好的情況是,你可以實現這些方法的三個重載:
public static TElem GetOrNew<TList, TElem>(this TList collection, int key)
where TList : IList<TElem>, TElem:new()
{
...
}
public static TElem Set<TList, TElem>(this TList collection, int key, TElem value)
where TList: IList<TElem>
{
...
}
public static TVal GetOrNew<TDict, TKey, TVal>(this TDict collection, TKey key)
where TDict : IDictionary<TKey, TVal>, TVal : new()
{
...
}
public static TVal Set<TDict, TKey, TVal>(this TDict collection, TKey key, TVal value)
where TDict : IDictionary<TKey, TVal>
{
...
}
public static TVal GetOrNew<TColl, TKey, TVal>(this TDict collection, TKey key)
where TColl : IIndexable<TKey, TVal>, TVal: new()
{
...
}
public static TVal Set<TColl, TKey, TVal>(this TDict collection, TKey key, TVal value)
where TColl : IIndexable<TKey, TVal>
{
...
}
...這將允許您使用索引器(包括Array,實際上用於實現IList)在第90百分位的對象上使用此方法集。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.