简体   繁体   中英

Generic method to replace two

I would like to make below methods generic, this method makes a search using a search service, and all possible URL's are in a dictionary.

public XDocument DoSearchForTypeA()
{
    return searchService.Search(dictionary["optiona"]);
}

public XDocument DoSearchForTypeB()
{
    return searchService.Search(dictionary["optionb"]);
}

I was thinking on doing something like this:

public XDocument DoSearch<T>()
{
    if(typeof(T)==typeof(MyTypeA))
    {
        return searchService.Search(dictionary["optiona"]);
    }
    return searchService.Search(dictionary["optionb"]);
}

I see my solution really awful. Mainly cause i dont like the switches or ifs parsing each type. It makes the code not so flexible for scale it.

I would like to have a more elegant solution, but I have the feeling that this is not the best example for using generic methods. Could you give me some advices on this reflection?

Dictionary is one of the options:

private static Dictionary<Type, String> s_Search = new Dictionary<Type, String>()
{
    {typeof(MyTypeA), "optiona"},
    {typeof(MyTypeB), "optionb"}
}

...

public XDocument DoSearch<T>()
{ 
    return searchService.Search(dictionary[s_Search(typeof(T))]);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM