【问题标题】:Optional parameters on delegates doesn't work properly [duplicate]代表上的可选参数无法正常工作[重复]
【发布时间】:2011-08-03 22:05:20
【问题描述】:

为什么这段代码不能编译?

delegate int xxx(bool x = true);

xxx test = f;

int f()
{
   return 4;
}

【问题讨论】:

    标签: c# delegates optional-parameters


    【解决方案1】:

    可选参数用于调用端 - 而不是像单方法接口实现那样有效。例如,这个应该编译:

    delegate void SimpleDelegate(bool x = true);
    
    static void Main()
    {
        SimpleDelegate x = Foo;
        x(); // Will print "True"
    }
    
    static void Foo(bool y)
    {
        Console.WriteLine(y);
    }
    

    【讨论】:

      【解决方案2】:

      test(false) 会发生什么?它会破坏堆栈,因为签名必须匹配。

      【讨论】:

        【解决方案3】:

        试试这个方法:

        static int f(bool a)
        {
          return 4;
        }
        

        【讨论】:

          【解决方案4】:

          因为可选参数不会改变方法的底层签名,这对委托很重要。

          如果您不使用它,您的代码所期望的是不在方法签名中的可选参数 - 这是不正确的。

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-08-10
            • 2017-04-04
            • 1970-01-01
            • 2017-07-15
            • 2015-09-06
            相关资源
            最近更新 更多