4

所以我只是在考虑函数重载......

重载的方法共享相同的名称但具有唯一的签名。参数数量、参数类型或两者必须不同。不能仅根据不同的返回类型来重载函数。

那么在下面的例子中,为什么要重载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())每时每刻

4

2 回答 2

1

我不明白为什么它比使用可选参数更理想

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

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

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
    }
}
于 2013-05-28T11:01:04.250 回答
0

In your example the three overloads aren't equivalent to the method with optional parameters. setName(string last) states that the minimum data given is the last name, where public void setName(string first, string middle = "", string last = "") doesn't allow you to ommit first name. If you want to ommit middle name in the call of the method with optional parameters you would have to have setName("barack", last: "obama").

It would be somewhat better to have method with optional parameters like this:

public void setName(string last, string first= "", string middle = "")

But this ruins the natural order of names and allows you to set middle name without specifing first (setName("barack", middle: "hussein");) which the three overloads prohibit.

于 2013-05-28T10:21:16.453 回答