带有可选参数的构造函数 - 好还是坏?

时间:2015-03-26 18:39:57

标签: c#

我见过很多像这样的代码:

class A 
{
    public string a;
    public string b;
    public int c;
    public int d;

    public A (string a = "something", string b = "something", int c = 123, int d = 456) 
    {
        this.a = a;
        this.b = b;
        this.c = c;
        this.d = d;
    }
}

我认为滥用可选参数。不像这样制作构造函数会更好:

public A() 
{
    this.a = "something";
    this.b = "something";
    this.c = 123;
    this.d = 456;
}

以后用户可以这样做:

A a = new A() { a = "myString", c = 1000 };

是否有任何特殊原因使构造函数的第一个版本比第二个版本更好?

0 个答案:

没有答案