接口Interface学习

date
Dec 18, 2021
slug
10028
status
Published
tags
C#
summary
type
Post
从IComparable接口的定义可以看到其中方法CompareTo并没有实现,只有一个分号表示。
#region Assembly mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089
// C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.5\mscorlib.dll
#endregion

using System.Runtime.InteropServices;

namespace System
{
    //
    // Summary:
    //     Defines a generalized type-specific comparison method that a value type or class
    //     implements to order or sort its instances.
    [ComVisible(true)]
    public interface IComparable
    {
        //
        // Summary:
        //     Compares the current instance with another object of the same type and returns
        //     an integer that indicates whether the current instance precedes, follows, or
        //     occurs in the same position in the sort order as the other object.
        //
        // Parameters:
        //   obj:
        //     An object to compare with this instance.
        //
        // Returns:
        //     A value that indicates the relative order of the objects being compared. The
        //     return value has these meanings: Value Meaning Less than zero This instance precedes
        //     obj in the sort order. Zero This instance occurs in the same position in the
        //     sort order as obj. Greater than zero This instance follows obj in the sort order.
        //
        // Exceptions:
        //   T:System.ArgumentException:
        //     obj is not the same type as this instance.
        int CompareTo(object obj);
    }
}
自定义的MyClass继承IComparable接口后必须实现它的CompareTo方法,如何实现要看.NET文档接口定义中CompareTo的说明:Value Meaning Less than zero This instance precedes obj in the sort order. Zero This instance occurs in the same position in the sort order as obj. Greater than zero This instance follows obj in the sort order.
using System;

class MyClass : IComparable                           // Class implements interface.
{
    public int TheValue;
    public int CompareTo(object obj)                 // Implement the method.
    {
        MyClass mc = (MyClass)obj;
        if (TheValue < mc.TheValue)
            return -1;
        if (TheValue > mc.TheValue)
            return 1;
        return 0;
    }
}
class Program
{
    static void PrintOut(string s, MyClass[] mc)
    {
        Console.Write(s);
        foreach (var m in mc)
            Console.Write("{0} ", m.TheValue);
        Console.WriteLine("");
    }
    static void Main()
    {
        var myInt = new[] { 20, 4, 16, 9, 2 };
        MyClass[] mcArr = new MyClass[5];               // Create array of MyClass objs.
        for (int i = 0; i < 5; i++)                   // Initialize the array.
        {
            mcArr[i] = new MyClass();
            mcArr[i].TheValue = myInt[i];
        }
        PrintOut("Initial Order: ", mcArr);           // Print the initial array.
        Array.Sort(mcArr);                            // Sort the array.
        PrintOut("Sorted Order:  ", mcArr);            // Print the sorted array.
    }
}
然后才可以使用Sort方法,从Sort方法的Summary可以看到它用了IComparable接口
//
        // Summary:
        //     Sorts the elements in an entire System.Array using the System.IComparable`1 generic
        //     interface implementation of each element of the System.Array.
        //
        // Parameters:
        //   array:
        //     The one-dimensional, zero-based System.Array to sort.
        //
        // Type parameters:
        //   T:
        //     The type of the elements of the array.
        //
        // Exceptions:
        //   T:System.ArgumentNullException:
        //     array is null.
        //
        //   T:System.InvalidOperationException:
        //     One or more elements in array do not implement the System.IComparable`1 generic
        //     interface.
        [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)]
        public static void Sort<T>(T[] array);
notion image
 

© Wen Bo 2021 - 2022