所以我只想到函数重载……
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 } }