简体   繁体   中英

C# - Define preference for generic function overloads

I have a very simple recursively defined function that prints out the contents of any list, defined as such;

    static string ShowList<T>(IEnumerable<T> iterable)
    {
        return "[" + string.Join(", ", iterable.Select(e => ShowList(e))) + "]";
    }

    static string ShowList(string str)
    {
        return $"\"${str}\"";
    }

    static string ShowList<T>(T elem)
    {
        return elem.ToString();
    }

As you can see, the lowest override is a catch all which applies to any argument. The highest overload only applies to arguments which are enumerables. Ideally I want it to check against and run the most specific overloads first, and then if they all fail, use the general case. But what I find is that it always goes straight for the general case immediately, and just prints out Systems.Generic.Containers.List1[] . Is it possible to give certain overloads more precedence than others, so that the compiler will automatically try those before others?

It looks to me that because e (in the delegate for iterable.Select) is of type T, therefore the compiler is going to use the type T overload. I would suggest, that since all it does is return the ToString() method, eliminate it and change the call in the delegate to ShowList(e.ToString()) . If the ToString() is overloaded you'll most likely get meaningful data, otherwise you'll the object type data.

As for sending the List<List<T>> you'll need a different overload that one won't accept it.

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