我想刪除具有可變數量的參數的System.Func集合的重複代碼。 (這用於允許代碼「掛鉤」到其他組件的邏輯中。) 因此,我試圖刪除幾個幾乎相同的方法,並使用泛型方法代替。嵌套泛型類型:重用外部類型參數
爲了使它工作,我將它們包裝在一個HookContainer類中,並使它實現了一個通用接口。
public interface IHookContainer
{
void Add<TFunc> (string filterName, int priority, KeyValuePair<string, TFunc> action);
}
public class HookContainer<T>:IHookContainer
{
Dictionary<string,OrderedDictionary<string,T>> dict = new Dictionary<string, OrderedDictionary<string, T>>();
public void Add<T> (string filterName, int priority, KeyValuePair<string, T> action)
{
// Add an item to the Dictionary
}
}
這讓我把他們都在,我可以與類型
Dictionary<Type,IHookContainer> containers = new Dictionary<Type, IHookContainer>(){
{
typeof(HookContainer<System.Func<object,object>>),new HookContainer<System.Func<object,object>>()
},
// More dictionary entries like this (with more parameters)
};
public string AddFilter<T> (string filterName, T action, string filterTag = null, int priority=0)
{
KeyValuePair<string, T> data = new KeyValuePair<string, T> (filterTag, action);
if (containers.ContainsKey (typeof(T))) {
IHookContainer container = containers [typeof(T)];
container.Add<T> (filterName, dictPriority, data);
}
return filterTag;
}
現在我得到一個編譯錯誤說訪問一個字典:
cannot convert `System.Collections.Generic.KeyValuePair<string,T>'
expression to type `System.Collections.Generic.KeyValuePair<string,T>'
所以這是很明顯缺乏一些我認爲理所當然的信息。或者我想錯了。或兩者。 爲什麼不能將類型轉換爲...本身?
我明顯不能使用泛型類中的相同類型參數作爲泛型方法(如果已實現的接口)。可悲的是,這種類型也無法推斷。有什麼辦法可以做到這一點?
還有一個警告,即類型參數名稱與外部類型參數相同。我能告訴編譯器這是完全意圖的嗎?
感謝您的任何幫助。我使用C#4.0
更新:
我可以得到代碼與第二個類型參數聲明HookContainer和使用這種傳遞入Add
方法工作。
所以它現在看起來是這樣的:
public class HookContainer<T,U>:IHookContainer
{
Dictionary<string,OrderedDictionary<string,T>> dict = new Dictionary<string, OrderedDictionary<string, T>>();
public void Add<U> (string filterName, int priority, KeyValuePair<string, T> action)
{
// Add an item to the Dictionary
}
}
這當然需要我去冗餘通過容器的類型兩次聲明字典時:
Dictionary<Type,IHookContainer> containers = new Dictionary<Type, IHookContainer>(){
{
typeof(HookContainer<System.Func<object,object>,System.Func<object,object>>),new HookContainer<System.Func<object,object>,System.Func<object,object>>()
}
};
所以雖然這可能有效,但它看起來和感覺很荒謬。有沒有什麼辦法只是(重新)使用一個單一的類型參數?
我得到「非一般類型‘System.Collections.Specialized.OrderedDictionary’不能與類型參數一起使用。」 – MJVC
我正在使用OrderedDictionary的這個實現https://github.com/johndkane/GenericOrderedDictionary/blob/master/Library/OrderedDictionary%602.cs – Arbelzapf