您能用可选参数向我解释C#的这种奇怪行为吗? [英] Can you explain me this strange behaviour of c# with optional arguments?

查看:84
本文介绍了您能用可选参数向我解释C#的这种奇怪行为吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
关于重写方法的C#可选参数

Possible Duplicate:
C# optional parameters on overridden methods

这是以下代码的输出:

Peter: -1
Peter: 0
Fred: 1
Fred: 1

您能解释一下为什么彼得p.TellYourAge()p.DoSomething()的称呼不相同吗?

Can you explain me why the call of Peter p.TellYourAge() and p.DoSomething() is not identical?

这里是您自己尝试使用的代码(VS2010和FW 4):

Here the code to try it yourself (VS2010 and FW 4):

    static void Main(string[] args)
    {
        Peter p = new Peter();
        p.TellYourAge(); // expected -1, result: -1
        p.DoSomething(); // expected -1, result: 0

        Fred f = new Fred();
        f.TellYourAge(1); // expected 1, result: 1
        f.DoSomething(); // expected 1, result: 1

        Console.ReadKey();
    }
}

public abstract class Person
{
    public abstract void TellYourAge(int age); // abstract method without default value
}

public class Peter : Person
{
    public override void TellYourAge(int age = -1) // override with default value
    {
        Console.WriteLine("Peter: " + age);
    }

    public void DoSomething()
    {
        TellYourAge();
    }
}

public class Fred : Person
{
    public override void TellYourAge(int age) // override without default value
    {
        Console.WriteLine("Fred: " + age);
    }

    public void DoSomething()
    {
        TellYourAge(1);
    }
}

推荐答案

如果您恰巧使用Resharper,则会向您发出以下警告/通知.

If you happen to use Resharper, it will give you the following warning / notification.

可选参数默认值与基本方法void TellYourAge(int age)中的参数年龄不同."

"Optional parameter default value differs from parameter age in base method void TellYourAge(int age)."

当您混合使用可选参数值和继承时,请注意.默认参数值是在编译时而不是运行时解析的.默认值属于被调用的引用类型.在这里,它解析为Person类型,并使用整数的默认值0而不是-1.

Look out when you mix optional parameter values and inheritance. Default parameter values are resolved at compile time, not runtime. The default belongs to the reference type being called. Here it resolves to the Person type and it uses the default value of an integer which is 0, instead of -1.

您可以在此处找到有关可选参数的常见陷阱的一些信息:

You can find some information about common pitfalls regarding optional parameters here:

http://geekswithblogs.net/BlackRabbitCoder/archive/2010/06/17/c-optional-parameters---pros-and-pitfalls.aspx

如果要以这种方式使用它,可以轻松修复.调用方法TellYourAge时,明确指定关键字"this".这样,所需的默认值将在编译时确定.

Easy fix if you want to use it this way. Explicitly specify the keyword 'this' when calling the method TellYourAge. This way the desired default value will be determined at compile time.

public void DoSomething()
{
    this.TellYourAge();
}

这篇关于您能用可选参数向我解释C#的这种奇怪行为吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆