关于c#:为什么在接口上定义的实现中允许使用不同的默认值?

Why are different default values permitted in implementations from those defined on interface?

本问题已经有最佳答案,请猛点这里访问。

我最近遇到了以下行为:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
internal interface IOptionalParamTest
{
    void PrintMessage(string message ="Hello");
}

class OptionalParamTest : IOptionalParamTest
{
    public void PrintMessage(string message ="Goodbye")
    {
        Console.WriteLine(message);
    }
}

internal class Program
{
    static void Main()
    {
        IOptionalParamTest usingInterface = new OptionalParamTest();
        usingInterface.PrintMessage(); // prints"Hello"

        OptionalParamTest usingConcrete = new OptionalParamTest();
        usingConcrete.PrintMessage();// prints"Goodbye"
    }
}

我的问题是:为什么编译器不拒绝使用与接口上定义的默认值不同的printmessage实现?


(P)The call printmessage();is just syntactic sugar.There is no method printmessage(……)that take Zero parameters.The compiler simply inserts the correct value.So,the compiler changes the first call to:(p)字母名称(P)因为使用脑电容的竞争时间类型是IOPTIONALPARAMPATES。(p)(P)The compile-time type of usingconcrete is optional paramet,so it looks there for the value to insert and the call becomes(p)字母名称


(P)Interface implementations simply don't use default values(rather:it is only the call-site that used the default values);it is allowed on regular method declarations,so that you can still use the default parameter value feature-but there is no requirement for it to be the same value.If we add an explicit interface implementation,it becomes more interesting:(p)字母名称(P)And in answer to the question"What happens here?"A compiler warning:(p)布尔奇1