gpt4 book ai didi

c# - 如何调用默认方法而不是具体实现

转载 作者:行者123 更新时间:2023-12-02 00:00:35 25 4
gpt4 key购买 nike

为什么 C# 8 中默认接口(interface)方法的行为发生了变化?过去的代码如下(默认接口(interface)方法演示时未发布):

interface IDefaultInterfaceMethod
{
// By default, this method will be virtual, and the virtual keyword can be here used!
virtual void DefaultMethod()
{
Console.WriteLine("I am a default method in the interface!");
}

}

interface IOverrideDefaultInterfaceMethod : IDefaultInterfaceMethod
{
void IDefaultInterfaceMethod.DefaultMethod()
{
Console.WriteLine("I am an overridden default method!");
}
}

class AnyClass : IDefaultInterfaceMethod, IOverrideDefaultInterfaceMethod
{
}

class Program
{
static void Main()
{
IDefaultInterfaceMethod anyClass = new AnyClass();
anyClass.DefaultMethod();

IOverrideDefaultInterfaceMethod anyClassOverridden = new AnyClass();
anyClassOverridden.DefaultMethod();
}
}

有以下输出:

控制台输出:

I am a default method in the interface!
I am an overridden default method!

但是在 C# 8 最新版本中,上面的代码会产生以下输出:

控制台输出:

I am an overridden default method!
I am an overridden default method!

任何人都可以向我解释为什么这种行为会改变吗?

注意:

IDefaultInterfaceMethod anyClass = new AnyClass(); anyClass.DefaultMethod();

((IDefaultInterfaceMethod) anyClass).DefaultMethod(); // STILL the same problem!??

最佳答案

我怀疑更好的问题是:

How can I call the default method instead of the concrete implementation?

该功能已计划但已 cut from C# 8 in April 2019 ,因为有效的实现需要运行时的支持。发布前未能及时添​​加。该功能必须适用于 C# 和 VB.NET - F# 无论如何都不喜欢接口(interface)。

if B.M is not present at run time, A.M() will be called. For base() and interfaces, this is not supported by the runtime, so the call will throw an exception instead. We'd like to add support for this in the runtime, but it is too expensive to make this release.

We have some workarounds, but they do not have the behavior we want, and are not the preferred codegen.

Our implementation for C# is somewhat workable, although not exactly what we would like, but the VB implementation would be much more difficult. Moreover, the implementation for VB would require the interface implementation methods to be public API surface.

它会起作用 through a base() call类似于类(class)的运作方式。复制提案示例:

interface I1
{
void M(int) { }
}

interface I2
{
void M(short) { }
}

interface I3
{
override void I1.M(int) { }
}

interface I4 : I3
{
void M2()
{
base(I3).M(0) // What does this do?
}
}

关于c# - 如何调用默认方法而不是具体实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60569584/

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