C# 函数引用重载方法

C# function reference to an overloaded method

我有一个带有一些重载方法的静态 class。我想知道是否有一种 simple/elegant 方法可以将对正确重载方法的引用传递给我的另一个方法。

ObjectComparer.cs:

internal static class ObjectComparer {
    internal static void AssertAreEqual(Company expected, Company actual) {
        // ...
    }

    internal static void AssertAreEqual(Contact expected, Contact actual) {
        // ...
    }
}

CollectionComparer.cs:

internal static class CollectionComparer {
    internal static void AssertAreEqual<T>(List<T> expected, List<T> actual, Action<T, T> comparer) 
    {
        Assert.AreEqual(expected.Count, actual.Count);

        for (var i = 0; i < expected.Count; i++) 
        {
            comparer(expected[i], actual[i]);
        }
    }
}

CompanyRepositoryUnitTest.cs:

[TestMethod]
public void GetAllCompaniesTest()
{
    // some work that creates 2 collections: expectedCompanies and actualCompanies

    // I am hoping I can write the following method 
    // but I am getting an error over here saying 
    // The best overloaded method ... has invalid arguments
    CollectionComparer.AssertAreEqual(expectedCompanies, actualCompanies, ObjectComparer.AssertAreEqual);
}

编辑

事实证明编译器在抱怨我的其他参数之一:actualCompanies。它是一个 ICollection 而不是 List。

抱歉。这是一个非常愚蠢的错误。

您可能希望在作为 AssertAreEqual 参数传递时按如下方式实例化 Action

var action=  new Action<Company,Company>(ObjectComparer.AssertAreEqual);
CollectionComparer.AssertAreEqual(expectedCompanies, actualCompanies, action); 

对于 Contact 你可以简单地做:

var action=  new Action<Contact,Contact>(ObjectComparer.AssertAreEqual);

我认为这也会有所帮助,如果你的比较器是静态的并且永远不会改变,你可能不需要每次都传递它。

internal static class CollectionComparer {
internal static void AssertAreEqual<T>(List<T> expected, List<T> actual) 
    {
        Assert.AreEqual(expected.Count, actual.Count);

        for (var i = 0; i < expected.Count; i++) 
        {
            CollectionComparer.AssertAreEqual(expected[i], actual[i]);
        }
    }
}