简体   繁体   English

C#-为泛型函数重载定义首选项

[英]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. 如您所见,最低的替代是适用于所有参数的catch全部。 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[] . 但是我发现,在一般情况下,它总是立即可用,并且只打印出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. 在我看来,由于e (在iterable.Select的委托中)的类型为T,因此编译器将使用类型T重载。 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()) . 我建议,既然ShowList(e.ToString())就是返回ToString()方法,请消除它,并将委托中的调用更改为ShowList(e.ToString()) If the ToString() is overloaded you'll most likely get meaningful data, otherwise you'll the object type data. 如果ToString()被重载,则很可能会获得有意义的数据,否则将获得对象类型的数据。

As for sending the List<List<T>> you'll need a different overload that one won't accept it. 至于发送List<List<T>>您将需要不同的重载,而这个重载是不会接受的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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