接口 #

一、接口概述 #

接口定义了一组方法、属性、事件和索引器的契约,不包含实现。

1.1 接口特点 #

  • 只定义契约,不包含实现(C# 8之前)
  • 成员默认public
  • 不能实例化
  • 可以多实现
  • 支持继承

1.2 基本语法 #

csharp
public interface IAnimal
{
    string Name { get; set; }
    void MakeSound();
    void Move();
}

二、接口定义 #

2.1 方法定义 #

csharp
public interface ICalculator
{
    int Add(int a, int b);
    int Subtract(int a, int b);
    int Multiply(int a, int b);
    int Divide(int a, int b);
}

2.2 属性定义 #

csharp
public interface IPerson
{
    string Name { get; set; }
    int Age { get; }
    string FullName { get; }
}

2.3 事件定义 #

csharp
public interface INotifyValueChanged
{
    event EventHandler ValueChanged;
    int Value { get; set; }
}

2.4 索引器定义 #

csharp
public interface IStringCollection
{
    string this[int index] { get; set; }
    int Count { get; }
}

三、接口实现 #

3.1 隐式实现 #

csharp
public interface IDrawable
{
    void Draw();
}

public class Rectangle : IDrawable
{
    public void Draw()
    {
        Console.WriteLine("绘制矩形");
    }
}

IDrawable drawable = new Rectangle();
drawable.Draw();

Rectangle rect = new Rectangle();
rect.Draw();

3.2 显式实现 #

csharp
public interface IReadable
{
    string Read();
}

public interface IWritable
{
    string Read();
    void Write(string content);
}

public class Document : IReadable, IWritable
{
    string IReadable.Read()
    {
        return "从可读接口读取";
    }
    
    string IWritable.Read()
    {
        return "从可写接口读取";
    }
    
    public void Write(string content)
    {
        Console.WriteLine($"写入:{content}");
    }
}

var doc = new Document();

IReadable readable = doc;
Console.WriteLine(readable.Read());

IWritable writable = doc;
Console.WriteLine(writable.Read());

3.3 混合实现 #

csharp
public interface IRepository
{
    void Add<T>(T entity);
    void Delete<T>(T entity);
    T GetById<T>(int id);
}

public class Repository : IRepository
{
    public void Add<T>(T entity)
    {
        Console.WriteLine($"添加:{entity}");
    }
    
    void IRepository.Delete<T>(T entity)
    {
        Console.WriteLine($"删除:{entity}");
    }
    
    public T GetById<T>(int id)
    {
        Console.WriteLine($"获取ID为{id}的{typeof(T).Name}");
        return default;
    }
}

四、接口继承 #

4.1 接口继承接口 #

csharp
public interface IReadable
{
    string Read();
}

public interface IWritable
{
    void Write(string content);
}

public interface IFile : IReadable, IWritable
{
    string Path { get; }
    void Open();
    void Close();
}

public class TextFile : IFile
{
    public string Path { get; }
    
    public TextFile(string path)
    {
        Path = path;
    }
    
    public string Read() => "文件内容";
    
    public void Write(string content) => Console.WriteLine($"写入:{content}");
    
    public void Open() => Console.WriteLine($"打开文件:{Path}");
    
    public void Close() => Console.WriteLine("关闭文件");
}

4.2 类继承与接口 #

csharp
public class Animal
{
    public string Name { get; set; }
}

public interface IFlyable
{
    void Fly();
}

public interface ISwimmable
{
    void Swim();
}

public class Duck : Animal, IFlyable, ISwimmable
{
    public void Fly() => Console.WriteLine($"{Name}在飞");
    public void Swim() => Console.WriteLine($"{Name}在游泳");
}

五、默认接口方法(C# 8+) #

5.1 定义默认实现 #

csharp
public interface ILogger
{
    void Log(string message)
    {
        Console.WriteLine($"[Log] {message}");
    }
    
    void LogError(string message)
    {
        Console.WriteLine($"[Error] {message}");
    }
    
    void LogWarning(string message)
    {
        Console.WriteLine($"[Warning] {message}");
    }
}

public class ConsoleLogger : ILogger
{
}

var logger = new ConsoleLogger();
ILogger iLogger = logger;
iLogger.Log("Hello");

5.2 重写默认方法 #

csharp
public interface ILogger
{
    void Log(string message)
    {
        Console.WriteLine($"[Default] {message}");
    }
}

public class CustomLogger : ILogger
{
    public void Log(string message)
    {
        Console.WriteLine($"[Custom] {message}");
    }
}

六、接口多态 #

6.1 多态调用 #

csharp
public interface IShape
{
    double Area { get; }
    void Draw();
}

public class Rectangle : IShape
{
    public double Width { get; set; }
    public double Height { get; set; }
    public double Area => Width * Height;
    public void Draw() => Console.WriteLine("绘制矩形");
}

public class Circle : IShape
{
    public double Radius { get; set; }
    public double Area => Math.PI * Radius * Radius;
    public void Draw() => Console.WriteLine("绘制圆形");
}

var shapes = new List<IShape>
{
    new Rectangle { Width = 5, Height = 3 },
    new Circle { Radius = 4 }
};

foreach (var shape in shapes)
{
    shape.Draw();
    Console.WriteLine($"面积:{shape.Area}");
}

6.2 依赖注入 #

csharp
public interface IMessageService
{
    void Send(string to, string message);
}

public class EmailService : IMessageService
{
    public void Send(string to, string message)
    {
        Console.WriteLine($"发送邮件到 {to}: {message}");
    }
}

public class SmsService : IMessageService
{
    public void Send(string to, string message)
    {
        Console.WriteLine($"发送短信到 {to}: {message}");
    }
}

public class NotificationService
{
    private readonly IMessageService _messageService;
    
    public NotificationService(IMessageService messageService)
    {
        _messageService = messageService;
    }
    
    public void Notify(string user, string message)
    {
        _messageService.Send(user, message);
    }
}

七、常用接口 #

7.1 IEnumerable #

csharp
public class NumberSequence : IEnumerable<int>
{
    private readonly int[] _numbers;
    
    public NumberSequence(int[] numbers)
    {
        _numbers = numbers;
    }
    
    public IEnumerator<int> GetEnumerator()
    {
        return ((IEnumerable<int>)_numbers).GetEnumerator();
    }
    
    IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}

7.2 IComparable #

csharp
public class Person : IComparable<Person>
{
    public string Name { get; set; }
    public int Age { get; set; }
    
    public int CompareTo(Person other)
    {
        return Age.CompareTo(other.Age);
    }
}

var people = new List<Person>
{
    new Person { Name = "张三", Age = 25 },
    new Person { Name = "李四", Age = 20 },
    new Person { Name = "王五", Age = 30 }
};

people.Sort();

7.3 ICloneable #

csharp
public class Person : ICloneable
{
    public string Name { get; set; }
    public int Age { get; set; }
    
    public object Clone()
    {
        return new Person { Name = Name, Age = Age };
    }
}

var original = new Person { Name = "张三", Age = 25 };
var clone = (Person)original.Clone();

7.4 IDisposable #

csharp
public class ResourceHolder : IDisposable
{
    private bool _disposed = false;
    private IntPtr _handle;
    
    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
    
    protected virtual void Dispose(bool disposing)
    {
        if (!_disposed)
        {
            if (disposing)
            {
            }
            
            _handle = IntPtr.Zero;
            _disposed = true;
        }
    }
    
    ~ResourceHolder()
    {
        Dispose(false);
    }
}

using var resource = new ResourceHolder();

八、实战示例 #

8.1 支付系统 #

csharp
public interface IPaymentGateway
{
    bool ProcessPayment(decimal amount);
    bool Refund(string transactionId, decimal amount);
    PaymentStatus GetStatus(string transactionId);
}

public class StripeGateway : IPaymentGateway
{
    public bool ProcessPayment(decimal amount)
    {
        Console.WriteLine($"Stripe处理支付:{amount:C}");
        return true;
    }
    
    public bool Refund(string transactionId, decimal amount)
    {
        Console.WriteLine($"Stripe退款:{transactionId}");
        return true;
    }
    
    public PaymentStatus GetStatus(string transactionId)
    {
        return PaymentStatus.Completed;
    }
}

public class PayPalGateway : IPaymentGateway
{
    public bool ProcessPayment(decimal amount)
    {
        Console.WriteLine($"PayPal处理支付:{amount:C}");
        return true;
    }
    
    public bool Refund(string transactionId, decimal amount)
    {
        Console.WriteLine($"PayPal退款:{transactionId}");
        return true;
    }
    
    public PaymentStatus GetStatus(string transactionId)
    {
        return PaymentStatus.Completed;
    }
}

public enum PaymentStatus { Pending, Completed, Failed }

九、总结 #

接口要点:

要点 说明
interface关键字 定义接口
隐式实现 public方法
显式实现 接口名.方法名
多实现 实现多个接口
默认方法 C# 8+支持

下一步,让我们学习面向对象高级特性!

最后更新:2026-03-26