gpt4 book ai didi

c# - 显式实现的接口(interface)中的可选参数

转载 作者:行者123 更新时间:2023-11-30 17:09:41 27 4
gpt4 key购买 nike

public interface IFoo
{
void Foo(bool flag = true);
}

public class Test : IFoo
{
void IFoo.Foo(bool flag = true) //here compiler generates a warning
{

}
}

警告说给定的默认值将被忽略,因为它在不允许它的上下文中使用。

为什么显式实现的接口(interface)不允许使用可选参数?

最佳答案

显式实现的接口(interface)方法总是被调用,其编译时类型是接口(interface)的目标,而不是特定的实现。编译器查看由它“知道”正在调用的方法声明的可选参数。当它只知道目标表达式是 IFoo 类型时,您如何期望它知道从 Test.Foo 获取参数?

IFoo x = new Test();
x.Foo(); // How would the compiler know to look at the Test.Foo declaration here?

关于c# - 显式实现的接口(interface)中的可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12730458/

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