温馨提示×

C# interface的新特性了解吗

c#
小樊
86
2024-07-19 13:34:43
栏目: 编程语言

是的,C# 8.0引入了一些新的特性,包括接口中的默认实现、接口中的私有成员、接口中的静态成员和接口中的扩展方法。

  1. 默认实现:接口现在可以包含具有默认实现的方法。这意味着实现接口的类可以选择性地重写这些方法,而不是必须实现所有方法。
interface IExample
{
    void Method1();
    
    void Method2()
    {
        Console.WriteLine("Default implementation of Method2");
    }
}

class Example : IExample
{
    public void Method1()
    {
        Console.WriteLine("Implementation of Method1");
    }
}
  1. 私有成员:接口现在可以包含私有成员,这些成员只能在接口内部访问。
interface IExample
{
    private void PrivateMethod()
    {
        Console.WriteLine("Private method in interface");
    }
    
    void PublicMethod()
    {
        PrivateMethod();
    }
}
  1. 静态成员:接口现在可以包含静态成员,这些成员可以在接口上直接调用,而不需要实现接口的类。
interface IExample
{
    static void StaticMethod()
    {
        Console.WriteLine("Static method in interface");
    }
}

IExample.StaticMethod();
  1. 扩展方法:可以向接口添加扩展方法,这些方法可以在接口外部定义并用于扩展接口的功能。
interface IExample
{
    void Method();
}

static class ExampleExtensions
{
    public static void EnhancedMethod(this IExample example)
    {
        Console.WriteLine("Enhanced method in extension");
    }
}

class Example : IExample
{
    public void Method()
    {
        Console.WriteLine("Implementation of Method");
    }
}

Example example = new Example();
example.EnhancedMethod();

0