使用可选参数的方法重载 [英] Method Overloading with Optional Parameter

查看:85
本文介绍了使用可选参数的方法重载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有两个重载方法的类如下.

I have a class as follows with two overload method.

Class A
{
    public string x(string a, string b)
    {
        return "hello" + a + b;
    }

    public string x(string a, string b, string c = "bye")
    {
        return c + a + b;
    }
}

如果我从另一个具有两个参数的类中调用方法x,那么哪个方法将要执行,为什么?即

If I call the method x from another class with two parameters, then which method is going to execute and why? i.e,

string result = new A().x("Fname", "Lname");

我已经在控制台应用程序中对此进行了测试,并执行了带有2个参数的方法.有人可以解释吗?

I've tested this in my console application and the method with 2 parameters execute. Can someone explain this?

推荐答案

使用命名参数和可选参数会影响重载解析:

如果两个候选人被判定为同样出色,则优先考虑 没有可选参数的候选对象 在通话中被忽略了.这是一般情况的结果 重载解决方案优先考虑数量较少的候选对象 参数.

If two candidates are judged to be equally good, preference goes to a candidate that does not have optional parameters for which arguments were omitted in the call. This is a consequence of a general preference in overload resolution for candidates that have fewer parameters.

参考: MSDN

将调用带有2个参数string x(string a,string b)的上述规则方法.

Implying the above rule method with 2 parameters string x(string a,string b) will be called.

注意::如果两个重载方法都具有可选参数,则编译器将给出编译时歧义错误.

Note: If both overloaded methods have optional parameters then compiler will give compile-time ambiguity error.

这篇关于使用可选参数的方法重载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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