如何在c#中引用正确的非泛型重载?

Use*_*rol 0 c# generics overloading

我怎么写而不是??????? 选择适当的过载?

using System;
using System.Collections.Generic;

namespace ConsoleApplication2
{
    class A {}

    class B : A {}

    class C : A {}

    class Program
    {
        static void Main(string[] args)
        {
            var l1 = new List<C>();
            var l2 = new List<C>();
            Comparer<C>(l1, l2, ???????);
        }

        void Compare(C a, C b) { }

        void Compare(B a, B b) {}

        void Compare<T>(IList<T> a, IList<T> b, Action<T,T> comparator)
        {
            for (int i = 0; i < a.Count; i++)
                comparator(a[i], b[i]);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 5

您只需要使方法静态并修复方法名称.您甚至可以在初始调用时使用类型推断Compare:

static void Main(string[] args)
{
    var l1 = new List<C>();
    var l2 = new List<C>();

    Compare(l1, l2, Compare);
}

static void Compare(C a, C b) {}

static void Compare(B a, B b) {}

static void Compare<T>(IList<T> a, IList<T> b, Action<T,T> comparator)
{
    for (int i = 0; i < a.Count; i++)
        comparator(a[i], b[i]);
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下,没有歧义 - Compare(C, C)是该组中唯一可转换为a的方法Action<C, C>.如果您有Compare(A, A)方法,仍然会选择更具体的方法.如果你有以下情况,你会变得模棱两可:

static void Compare(A a, C b) {}
static void Compare(C a, A b) {}
Run Code Online (Sandbox Code Playgroud)

但是,我强烈建议在这种情况下尽量避免超载.为方法赋予不同的名称 - 它将使其更容易阅读,并避免任何歧义.