gpt4 book ai didi

c# - 接口(interface)c#中的具体方法

转载 作者:行者123 更新时间:2023-12-05 09:07:00 26 4
gpt4 key购买 nike

据我所知,我无法在 C# 的接口(interface)中创建具体方法,它应该会给我一个错误但是当我这样做的时候

interface IPerson
{
void x();
public void y()
{
Console.WriteLine("Welcome From Interface");
}
}

class Teacher : IPerson
{
public void x()
{

}
}

主要是

static void Main(string[] args)
{

IPerson p = new Teacher();
p.y();
Console.ReadKey();
}

输出变成=> Welcome From Interface为什么它没有给我报错?

最佳答案

此功能是 C# 8 中的新功能,称为 Default implementations in interfaces .

基本上,您可以在接口(interface)内提供一个方法的实现,该接口(interface)由实现它的类“继承”。

请注意,默认实现只能访问接口(interface)中的其他成员,并且不能声明接口(interface)具有属性以外的状态。一个典型的用例是当您提供的重载最终都链接到一个公共(public)重载中时,也许是参数最多的重载。

这使得实现接口(interface)变得更容易,但它也使得在接口(interface)中加入更多成员成为可能,而不必重新编译提供实现它们的类型的程序集,也不必将这些方法添加到这些类型。

注意实现接口(interface)的类仍然可以实现成员。然后您将拥有那个 实现。请注意,这不是继承,因此您不能从类中实现的方法中调用base.y() 来调用接口(interface)中的默认实现。使用默认实现,除非您在类中提供实际实现,否则该实现将完全替换接口(interface)中的默认实现。

另一个细节是,这些方法仅在您拥有接口(interface)类型的变量而不是具体类型的变量时可用。

所以虽然这有效:

IPerson p = new Person();
p.y();

这不是:

var p = new Person(); // p is now of type Person
p.y(); // CS1061 'Type' does not contain a definition for 'y' and no accessible extension method 'y' could be found

由于您的问题中已经有一个非常好的和简短的示例,我不会在此处添加更多代码,除非您要求澄清一些其他细节。

关于c# - 接口(interface)c#中的具体方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65395155/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com