gpt4 book ai didi

c# - 覆盖方法中的默认参数值

转载 作者:可可西里 更新时间:2023-11-01 07:48:07 25 4
gpt4 key购买 nike

在下面的代码中,对 Method2 的调用接收值为 False 的 Value 参数,即使基类根本没有为该参数声明默认值,而派生类将 True 声明为默认值。
可以说(正如此处类似示例所做的那样:C# optional parameters on overridden methods)编译器首先使用基类的方法声明(这是真的,因为可以通过在调用 Method1 前加上前缀 来更改此行为this.),但在这种情况下,基根本不声明默认值。
对此有合理的解释吗?

using System;

class Base
{
public virtual bool Method1(bool Value) { return true; }
public virtual bool Method2(bool Value) { return true; }
}

class Derived : Base
{
public override bool Method1(bool Value = true)
{
return Value;
}

public override bool Method2(bool Value = true)
{
return Method1();
}
}

class Program
{
static void Main(string[] args)
{
Derived a = new Derived();
Console.WriteLine("Call to Method1, expected: True, got: {0}", a.Method1());
Console.WriteLine("Call to Method2, expected: True, got: {0}", a.Method2());
}
}

输出:

Call to Method1, expected: True, got: TrueCall to Method2, expected: True, got: False

最佳答案

看起来这是一种错误。

这是你们谈论的链接,我想是今年早些时候的:

C# optional parameters on overridden methods

关于c# - 覆盖方法中的默认参数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11854107/

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