加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 函数重载与可选参数

发布时间:2020-12-15 21:51:40 所属栏目:百科 来源:网络整理
导读:所以我只想到函数重载…… Overloaded methods share the same name but have a unique signature. The number of parameters,types of parameters or both must be different. A function can’t be overloaded on the basis of a different return type al
所以我只想到函数重载……

Overloaded methods share the same name but have a unique signature. The number of parameters,types of parameters or both must be different. A function can’t be overloaded on the basis of a different return type alone.

所以在下面的例子中,为什么重载setName而不是使用中间名和姓氏值的可选参数?

class funOverload
{
    public string name;

    //overloaded functions
    public void setName(string last)
    {
        name = last;
    }

    public void setName(string first,string last)
    {
        name = first + "" + last;
    }

    public void setName(string first,string middle,string last)
    {
        name = first + "" + middle + "" + last;
    }

    //Entry point
    static void Main(string[] args)
    {
        funOverload obj = new funOverload();

        obj.setName("barack");
        obj.setName("barack "," obama ");
        obj.setName("barack ","hussian","obama");

    }
}

至少,使用以下内容可以减少需要编写的代码量:

public void setName(string first,string middle = "",string last = "")
{
   name = first + "" + middle + "" + last;

   // name = "barack" + "" + "";
}

//Entry point
static void Main(string[] args)
{
    funOverload obj = new funOverload();

    // could optionally set middle and last name values here as well
    obj.setName("barack");
 }

我理解重载的概念,但我没有得到的是为什么它比使用可选参数更合适(或反之亦然).

谁能解释一下?

仅供参考,这是我重载的第一个函数:http://pastebin.com/ynCuaay1
这个函数允许你调用带有或不带参数列表的MySqlContext.GetReader()…我认为它使代码比必须一直调用GetReader(sql,args.ToArray())更整洁

解决方法

I don’t get is why it would be a more desirable option than using optional parameters

具有默认值的参数具有一些限制,这在某些情况下可能很重要.

您可以为引用类型设置默认参数,而不是null(字符串参数除外):

class Foo
{
    public int Id { get; set; }
}

class Bar
{
    public Bar(Foo parent)
    {
    }

    public Bar()
        : this(new Foo { Id = 1 }) // this can't be done with default parameters
    {
    }
}

具有默认值的参数不能出现在常规参数之前,有时这可能是合适的:

class Foo
{
    public void Method(int i,string s,bool b) { }
    public void Method(string s,bool b) 
    {
        Method(0,s,b); // this can't be done with default parameters
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读