c#

C#接口有哪些不为人知的用法

小樊
84
2024-08-05 12:33:14
栏目: 编程语言

  1. 默认接口方法:C# 8.0 引入了默认接口方法的概念,允许在接口中定义带有默认实现的方法。这样可以减少实现接口的类需要重复编写相同代码的情况。
interface IMyInterface
{
    void MyMethod();

    void MyDefaultMethod()
    {
        Console.WriteLine("Default implementation of MyDefaultMethod");
    }
}
  1. 显式接口实现:在一个类实现多个接口时,可能会存在两个接口中有相同方法名的情况。此时可以使用显式接口实现来消除歧义。
interface IFirstInterface
{
    void MyMethod();
}

interface ISecondInterface
{
    void MyMethod();
}

class MyClass : IFirstInterface, ISecondInterface
{
    void IFirstInterface.MyMethod()
    {
        Console.WriteLine("Implementation of MyMethod for IFirstInterface");
    }

    void ISecondInterface.MyMethod()
    {
        Console.WriteLine("Implementation of MyMethod for ISecondInterface");
    }
}
  1. 接口的属性:接口中除了方法外还可以定义属性,通过属性可以实现对接口的状态读取和设置。
interface IMyInterface
{
    string MyProperty { get; set; }
}

class MyClass : IMyInterface
{
    public string MyProperty { get; set; }
}
  1. 接口继承:接口也可以继承其他接口,实现接口继承可以帮助组织和抽象代码结构。
interface IFirstInterface
{
    void MethodA();
}

interface ISecondInterface : IFirstInterface
{
    void MethodB();
}

class MyClass : ISecondInterface
{
    public void MethodA()
    {
        Console.WriteLine("Implementation of MethodA");
    }

    public void MethodB()
    {
        Console.WriteLine("Implementation of MethodB");
    }
}

0
看了该问题的人还看了