Problem Background: Use the Sort method to Sort Product objects.
The following are two signatures of the Sort method:
[Csharp]
Public void Sort (Comparison <T> comparison );
Public void Sort (IComparer <T> comparer );
One is the object that receives the IComparer <T> interface, and the other is the object that receives the Comparison <T> proxy.
I. Use interface objects
[Csharp]
Class ProductNameComparer: IComparer <Product>
{
Public int Compare (Product x, Product y)
{
Return x. Name. CompareTo (y. Name );
}
}
...
List <Product> products = Product. GetSampleProducts ();
Products. Sort (new ProductNameComparer ());
Foreach (Product product in products)
{
Console. WriteLine (product );
}
Ii. Use proxy
[Csharp]
Public int Compare (Product x, Product y)
{
Return x. Name. CompareTo (y. Name );
}
List <Product> products = Product. GetSampleProducts ();
Products. Sort (Compare );
Foreach (Product product in products)
{
Console. WriteLine (product. Name );
}
Think: what are the differences and connections between interfaces and Proxies?
An interface is a contract between classes and objects, and a proxy is a contract between methods. An interface object can only point to class objects that implement interfaces, and a proxy object can only point to methods that implement method signatures.
Iii. Anonymous Method
The anonymous method is a further extension of the proxy. It can pass the code block to the proxy object. The following code is rewritten using the anonymous method.
[Csharp]
List <Product> products = Product. GetSampleProducts ();
Products. Sort (delegate (Product x, Product y)
{Return x. Name. CompareTo (y. Name );}
);
Foreach (Product product in products)
{
Console. WriteLine (product );
}
Iv. lambda expressions
Lambda expressions are anonymous functions that can contain expressions and statements and can be used to create delegation and Expression Tree types. The lambda expressions are used to rewrite the above Code.
[Csharp]
List <Product> products = Product. GetSampleProducts ();
Products. Sort (x, y) => x. Name. CompareTo (y. Name ));
Foreach (Product product in products)
{
Console. WriteLine (product );
}