Auf Englisch lesen

Freigeben über


Comparison<T> Delegat

Definition

Stellt die Methode dar, die zwei Objekte desselben Typs vergleicht.

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

Typparameter

T

Der Typ der zu vergleichenden Objekte.

Dieser Typparameter ist kontravariant. Das bedeutet, dass Sie entweder den angegebenen Typ oder einen weniger abgeleiteten Typ verwenden können. Weitere Informationen zu Kovarianz und Kontravarianz finden Sie unter Kovarianz und Kontravarianz in Generics.

Parameter

x
T

Das erste zu vergleichende Objekt.

y
T

Das zweite zu vergleichende Objekt.

Rückgabewert

Int32

Eine ganze Zahl mit Vorzeichen, die die relativen Werte von x und y angibt, wie in der folgenden Tabelle veranschaulicht.

Wert Bedeutung
Kleiner als 0 x ist kleiner als y.
0 x ist gleich y.
Größer als 0 x ist größer als y.

Beispiele

Im folgenden Codebeispiel wird die Verwendung des Stellvertretungs mit der Comparison<T> Sort(Comparison<T>) Methodenüberladung veranschaulicht.

Im Codebeispiel wird eine alternative Vergleichsmethode für Zeichenfolgen definiert, benannt CompareDinosByLength. Diese Methode funktioniert wie folgt: Zunächst werden die Vergleiche für null, und ein Nullverweis wird als kleiner als eine Nicht-Null behandelt. Zweitens werden die Zeichenfolgenlängen verglichen, und die längere Zeichenfolge gilt als größer. Drittens, wenn die Längen gleich sind, werden normale Zeichenfolgenvergleiche verwendet.

Eine List<T> Zeichenfolge wird erstellt und mit vier Zeichenfolgen gefüllt, in keiner bestimmten Reihenfolge. Die Liste enthält auch eine leere Zeichenfolge und einen NULL-Verweis. Die Liste wird angezeigt, sortiert mit einem Comparison<T> generischen Stellvertretung, der die CompareDinosByLength Methode darstellt, und erneut angezeigt.

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"
 */

Im folgenden Beispiel wird der Comparison<T> Stellvertretung verwendet, um die Elemente einer Auflistung von CityInfo Objekten zu sortieren. CityInfo ist eine anwendungsdefinierte Klasse, die Informationen zu einer Stadt und ihrer Bevölkerung enthält. Das Beispiel definiert drei Methoden, CompareByName, CompareByPopulationund CompareByNames, die drei verschiedene Möglichkeiten zum Sortieren der CityInfo Objekte bieten. Jede Methode wird dem comparison Argument der Array.Sort<T>(T[], Comparison<T>) Methode zugewiesen.

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

Hinweise

Dieser Stellvertretung wird von der Methodenüberladung der Array Klasse und der Sort(Comparison<T>) Sort<T>(T[], Comparison<T>) Methodenüberladung List<T> der Klasse verwendet, um die Elemente eines Arrays oder einer Liste zu sortieren.

Erweiterungsmethoden

GetMethodInfo(Delegate)

Ruft ein Objekt ab, das die Methode darstellt, die vom angegebenen Delegaten dargestellt wird.

Gilt für

Produkt Versionen
.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

Siehe auch