2011-12-13 100 views
-1

我們有一個包含用於搜索的過濾條件的類。該類是一個包含值的過濾器標準字典。在運行時用C#泛型指定模板類

我想要做的就是這樣的事情。

protected string GetSearchValue(string name) 
{ 
    if (!FilterCache.HasFilter(name)) return string.Empty; 

    var filterType = FilterCache.GetFilterType(name); 

    var filter = FilterCache.GetFilter<filterType>(name); // <- This fails 

    if (filter == null || !filter.IsSet) return string.Empty; 

    return filter.Value.ToString();   
} 

GetFilterType看起來是這樣的:

public Type GetFilterType(string name) 
    { 
     return SearchElements[name].GetType(); 
    } 

最後,我想過濾的值,並將其返回到用戶界面。

+0

你能否告訴我們SearchElements'的'的定義和解釋更多你想要什麼類型過濾器是? – JaredPar

+1

http://stackoverflow.com/questions/513952/c-sharp-specifying-generic-collection-type-param-at-runtime可能的重複。 –

+0

[如何使用反射調用泛型方法?](http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) – nawfal

回答

0

你需要使用反射來調用在編譯時不知道類型參數一個通用的,就像這樣:

var getFilterGeneric = typeof(FilterCache) 
    .GetMethod("GetFilter") 
    .MakeGenericMethod(filterType) 
    .Invoke(typeof(FilterCache) /* or null */, name);