我正在尝试使用可选参数来了解它们如何与接口(interface)一起工作,但我遇到了一个奇怪的警告。我的设置是以下代码:
public interface ITestInterface
{
void TestOptional(int a = 5, int b = 10, object c = null);
}
public class TestClass : ITestInterface
{
void ITestInterface.TestOptional(int a = 5, int b = 5, object c = null)
{
Console.Write("a=" + a + " b=" + b + " c=" + c);
}
}
编译器给我以下警告:
- 为参数“a”指定的默认值将无效,因为它适用于在不允许可选参数的上下文中使用的成员
- 为参数“b”指定的默认值将无效,因为它适用于在不允许可选参数的上下文中使用的成员
- 为参数“c”指定的默认值将无效,因为它适用于在不允许可选参数的上下文中使用的成员
如果我使用以下代码运行它:
class Program
{
static void Main(string[] args)
{
ITestInterface test = new TestClass();
test.TestOptional();
Console.ReadLine();
}
}
如我所料,我得到了“a=5 b=10 c=
”的输出。
我的问题是什么是警告?它指的是什么上下文?
最佳答案
C# 中可选参数的问题是被调用者将对象视为 TestClass
还是 ITestInterface
。在第一种情况下,类中声明的值适用。在第二种情况下,接口(interface)中声明的值适用。这是因为编译器使用静态可用的类型信息来构造调用。在显式接口(interface)实现的情况下,该方法永远不会“为类”调用,总是“为接口(interface)”调用
10.6.1 中的 C# 语言规范指出:
If optional parameters occur in an implementing partial method declaration (§10.2.7) , an explicit interface member implementation (§13.4.1) or in a single-parameter indexer declaration (§10.9) the compiler should give a warning, since these members can never be invoked in a way that permits arguments to be omitted.
关于c# - 显式实现带有可选参数的接口(interface)的警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5683111/