Прочитать на английском

Поделиться через


Comparison<T> Делегат

Определение

Представляет метод, сравнивающий два объекта одного типа.

C#
public delegate int Comparison<in T>(T x, T y);
C#
public delegate int Comparison<T>(T x, T y);

Параметры типа

T

Тип сравниваемых объектов.

Это контравариантный параметр типа. Это означает, что вы можете использовать любой из указанных типов или любой тип, являющийся менее производным. Дополнительные сведения о ковариантности и контрвариантности см. в статье Ковариантность и контрвариантность в универсальных шаблонах.

Параметры

x
T

Первый из сравниваемых объектов.

y
T

Второй из сравниваемых объектов.

Возвращаемое значение

Int32

Знаковое целое число, которое определяет относительные значения параметров x и y, как показано в следующей таблице.

Значение Значение
Меньше 0 Значение x меньше y.
0 x равняется y.
Больше 0 Значение x больше значения y.

Примеры

В следующем примере кода показано использование делегата Comparison<T> с перегрузкой Sort(Comparison<T>) метода.

В примере кода определяется альтернативный метод сравнения строк с именем CompareDinosByLength. Этот метод работает следующим образом: во-первых, сравниваемые методы проверяются, nullа пустая ссылка обрабатывается как меньше, чем ненулевая. Во-вторых, сравниваются длины строк, а длинная строка считается большей. В-третьих, если длина равна, используется обычное сравнение строк.

Строка List<T> создается и заполняется четырьмя строками в определенном порядке. Список также включает пустую строку и пустую ссылку. Список отображается, сортируется с помощью универсального Comparison<T> делегата, представляющего CompareDinosByLength метод, и отображается снова.

C#
using System;
using System.Collections.Generic;

public class Example
{
    private static int CompareDinosByLength(string x, string y)
    {
        if (x == null)
        {
            if (y == null)
            {
                // If x is null and y is null, they're
                // equal.
                return 0;
            }
            else
            {
                // If x is null and y is not null, y
                // is greater.
                return -1;
            }
        }
        else
        {
            // If x is not null...
            //
            if (y == null)
                // ...and y is null, x is greater.
            {
                return 1;
            }
            else
            {
                // ...and y is not null, compare the
                // lengths of the two strings.
                //
                int retval = x.Length.CompareTo(y.Length);

                if (retval != 0)
                {
                    // If the strings are not of equal length,
                    // the longer string is greater.
                    //
                    return retval;
                }
                else
                {
                    // If the strings are of equal length,
                    // sort them with ordinary string comparison.
                    //
                    return x.CompareTo(y);
                }
            }
        }
    }

    public static void Main()
    {
        List<string> dinosaurs = new List<string>();
        dinosaurs.Add("Pachycephalosaurus");
        dinosaurs.Add("Amargasaurus");
        dinosaurs.Add("");
        dinosaurs.Add(null);
        dinosaurs.Add("Mamenchisaurus");
        dinosaurs.Add("Deinonychus");
        Display(dinosaurs);

        Console.WriteLine("\nSort with generic Comparison<string> delegate:");
        dinosaurs.Sort(CompareDinosByLength);
        Display(dinosaurs);
    }

    private static void Display(List<string> list)
    {
        Console.WriteLine();
        foreach( string s in list )
        {
            if (s == null)
                Console.WriteLine("(null)");
            else
                Console.WriteLine("\"{0}\"", s);
        }
    }
}

/* This code example produces the following output:

"Pachycephalosaurus"
"Amargasaurus"
""
(null)
"Mamenchisaurus"
"Deinonychus"

Sort with generic Comparison<string> delegate:

(null)
""
"Deinonychus"
"Amargasaurus"
"Mamenchisaurus"
"Pachycephalosaurus"
 */

В следующем примере делегат используется Comparison<T> для сортировки элементов коллекции CityInfo объектов. CityInfo — это определяемый приложением класс, содержащий сведения о городе и его населении. В этом примере определяются три метода, CompareByName``CompareByPopulationа также CompareByNamesтри различных способа упорядочивания CityInfo объектов. Каждому методу comparison присваивается аргумент Array.Sort<T>(T[], Comparison<T>) метода.

C#
using System;

public class CityInfo
{
   string cityName;
   string countryName;
   int pop2010;

   public CityInfo(string name, string country, int pop2010)
   {
      this.cityName = name;
      this.countryName = country;
      this.pop2010 = pop2010;
   }

   public string City
   { get { return this.cityName; } }

   public string Country
   { get { return this.countryName; } }

   public int Population
   { get { return this.pop2010; } }

   public static int CompareByName(CityInfo city1, CityInfo city2)
   {
      return String.Compare(city1.City, city2.City);
   }

   public static int CompareByPopulation(CityInfo city1, CityInfo city2)
   {
      return city1.Population.CompareTo(city2.Population);
   }

   public static int CompareByNames(CityInfo city1, CityInfo city2)
   {
      return String.Compare(city1.Country + city1.City, city2.Country + city2.City);
   }
}

public class Example
{
   public static void Main()
   {
      CityInfo NYC = new CityInfo("New York City", "United States of America", 8175133 );
      CityInfo Det = new CityInfo("Detroit", "United States of America", 713777);
      CityInfo Paris = new CityInfo("Paris", "France",  2193031);
      CityInfo[] cities = { NYC, Det, Paris };
      // Display ordered array.
      DisplayArray(cities);

      // Sort array by city name.
      Array.Sort(cities, CityInfo.CompareByName);
      DisplayArray(cities);

      // Sort array by population.
      Array.Sort(cities, CityInfo.CompareByPopulation);
      DisplayArray(cities);

      // Sort array by country + city name.
      Array.Sort(cities, CityInfo.CompareByNames);
      DisplayArray(cities);
   }

   private static void DisplayArray(CityInfo[] cities)
   {
      Console.WriteLine("{0,-20} {1,-25} {2,10}", "City", "Country", "Population");
      foreach (var city in cities)
         Console.WriteLine("{0,-20} {1,-25} {2,10:N0}", city.City,
                           city.Country, city.Population);

      Console.WriteLine();
   }
}
// The example displays the following output:
//     City                 Country                   Population
//     New York City        United States of America   8,175,133
//     Detroit              United States of America     713,777
//     Paris                France                     2,193,031
//
//     City                 Country                   Population
//     Detroit              United States of America     713,777
//     New York City        United States of America   8,175,133
//     Paris                France                     2,193,031
//
//     City                 Country                   Population
//     Detroit              United States of America     713,777
//     Paris                France                     2,193,031
//     New York City        United States of America   8,175,133
//
//     City                 Country                   Population
//     Paris                France                     2,193,031
//     Detroit              United States of America     713,777
//     New York City        United States of America   8,175,133

Комментарии

Этот делегат используется перегрузкой Sort<T>(T[], Comparison<T>) Array метода класса и Sort(Comparison<T>) перегрузкой List<T> метода класса для сортировки элементов массива или списка.

Методы расширения

GetMethodInfo(Delegate)

Получает объект, представляющий метод, представленный указанным делегатом.

Применяется к

Продукт Версии
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 2.0, 2.1
UWP 10.0

См. также раздел