Lambda to delegate resolution
I'm currently reading Jon Skeet's C# in depth 2nd edition and the following question came to my mind:
How's the compiler able开发者_开发问答 to choose between list.Sort(Comparison<T>)
and list.Sort(MyComparison<T>)
in the following example:
// MyComparison has the same signature as Comparison<in T>
public delegate int MyComparison<in T>(T x, T y);
public class MyList<T> : List<T>
{
// Sort is like Sort(Comparison<T>) except it takes a MyComparison<T> in parameter
public int Sort(MyComparison<T> comparison)
{
Console.WriteLine("Sort MyComparison<T>");
return -1;
}
}
MyList<Product> list = new MyList<Product>();
list.Sort((product1, product2) => product1.Name.CompareTo(product2.Name));
// Equivalent to
list.Sort(new MyComparison<Product>((product1, product2) => product1.Name.CompareTo(product2.Name)));
// But not equivalent to...
list.Sort(new Comparison<Product>((product1, product2) => product1.Name.CompareTo(product2.Name)));
Thanks in advance
It chooses that one because it's in the child class and it prefers those.
For example:
public class MyList<T> : List<T>
{
public int Sort2(MyComparison<T> comparison)
{
}
public int Sort2(Comparison<T> comparison)
{
}
}
In this case, it doesn't understand anymore and:
list.Sort2((product1, product2) => product1.Name.CompareTo(product2.Name));
and you get an "The call is ambigous" error.
If overload resolution comes across an applicable method, it will use that one in preference to any methods declared in base classes. So in this case, it's as if List<T>.Sort
didn't even exist, for the first two invocations.
The third invocation isn't applicable, so it will find List<T>.Sort
instead.
If you declared another overload for Sort
within MyList
(but taking Comparison<T>
instead of MyComparison<T>
) then the method call would be ambiguous.
See my overload resolution article for more details.
PS Hope you're enjoying the book :)
精彩评论