了解如何使用系统定义的接口

已完成

将系统定义的接口集成到 C# 应用程序中在许多实际编码方案中非常有用。 使用 C# 中的系统定义接口可以应用预定义的功能,使应用程序保持一致且稳定。

方法中使用的常见接口

.NET Framework 中的 C# 方法经常使用多个常见接口。 这些接口提供各种类实现的标准功能。

  • IComparable:用于比较对象。
  • IEnumerable:用于循环访问集合。
  • IDisposable:用于释放非托管资源。
  • IEquatable:用于定义相等比较。

实现系统定义的接口

若要实现系统定义的接口成员,实现类的对应成员必须是公共的,而不是 static,并且具有与接口成员相同的名称和签名。 实现接口的类或结构必须为所有声明成员提供实现,而无需接口提供默认实现。

.NET 中的系统定义接口通常使用占位符 T 来表示任何类型的接口。 例如,接口 IEquatable 在 .NET Framework 中定义,如下所示:

public interface IEquatable
{
    bool Equals(T other);
}

在类中实现此接口时,应将 T 替换为该类的具体类型。

例如,以下 Car 类实现 IEquatable 接口:

public class Car : IEquatable
{
    public string Make { get; set; }
    public string Model { get; set; }

    public bool Equals(Car other)
    {
        if (other == null) return false;
        return this.Make == other.Make && this.Model == other.Model;
    }
}

在此示例中,Car 取代了 T 中的 IEquatable,使其成为 IEquatable。 该Car类提供自己对Equals方法的实现,该方法检查当前Make对象的ModelCar属性是否等于otherCar对象的相应属性。

类的属性和索引器可以为接口中定义的属性或索引器定义额外的访问器。 例如,接口可能声明一个属性,该属性具有 get 访问器。 实现该接口的类可以声明同时具有 getset 访问器的相同属性。 下面是一个示例:

public interface IExampleInterface
{
    string Name { get; }
}

public class ExampleClass : IExampleInterface
{
    public string Name { get; set; }
}

在此示例中,IExampleInterface声明了一个具有Name访问器的属性getExampleClass 实现接口,并声明具有 getset 访问器的相同属性。

使用通用系统定义的接口

常见的系统定义接口,例如 IEnumerableIDisposableIComparable,常用于 .NET 应用程序中。 这些接口提供可以实现的标准方法,以确保不同类型的行为一致。

IEnumerable

IEnumerable 接口用于定义可以枚举的集合。 它包含一个方法, GetEnumerator该方法返回循环访问集合的枚举器。

public class MyCollection : IEnumerable
{
    private int[] _items = { 1, 2, 3, 4, 5 };

    public IEnumerator GetEnumerator()
    {
        for (int i = 0; i < _items.Length; i++)
        {
            yield return _items[i];
        }
    }

    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

IDisposable

IDisposable 接口用于释放非托管资源。 非托管资源是未使用 .NET 运行时处理的资源,例如文件句柄、网络连接等。使用后释放这些资源以防止内存泄漏和其他问题非常重要。 它包含一个方法, Dispose该方法被调用为释放资源。

public class ResourceHolder : IDisposable
{
    private bool _disposed = false;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this); // Prevents the garbage collector from calling the finalizer if Dispose has already been called.
    }

    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
                // Free managed resources
            }
            // Free unmanaged resources
            _disposed = true;
        }
    }

    ~ResourceHolder()
    {
        Dispose(false);
    }
}

IComparable

IComparable 接口用于定义用于比较类实例的方法。 它包含一个方法, CompareTo该方法将当前实例与同一类型的另一个对象进行比较。

public class Person : IComparable
{
    public string Name { get; set; }
    public int Age { get; set; }

    public int CompareTo(Person other)
    {
        if (other == null) return 1; // If 'other' is null, this instance is considered greater
        return this.Age.CompareTo(other.Age); // Returns negative value if  precedes 'other', 0 if same position, or postive value if follows 'other'.
    }
}

在此示例中,如果 other 为 null,则返回 1,指示当前实例被视为大于 null 引用。

C# 中的系统定义接口在创建高效、稳定且一致的应用程序方面发挥了关键作用。 它们提供可以跨不同类型实现的标准方法,确保行为中的统一性和可预测性。 通过了解并有效地实现这些接口,可以使用预定义的功能并减少重复代码的数量,使应用程序更易于维护和可靠。