我有一个带有一些重载方法的静态类。我想知道是否有一种简单/优雅的方式将对正确重载方法的引用传递给我的另一种方法。
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。
道歉。这是一个非常愚蠢的错误。
答案 0 :(得分:1)
您可能希望在传递Action
参数时将AssertAreEqual
实例化如下:
var action= new Action<Company,Company>(ObjectComparer.AssertAreEqual);
CollectionComparer.AssertAreEqual(expectedCompanies, actualCompanies, action);
对于Contact
你可以这样做:
var action= new Action<Contact,Contact>(ObjectComparer.AssertAreEqual);
答案 1 :(得分:1)
我认为这也有帮助,如果你的比较器是静态的并且永远不会改变,你可能不需要每次都传递它。
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]);
}
}
}