在没有编译时常量错误的另一个类构造函数中将类作为可选参数传递

时间:2013-07-16 17:18:06

标签: c# constructor compile-time-constant

在这个例子中假设我们有一个类:

public class Test
{
    int a;
    int b;
    int c;

    public Test(int a = 1, int b = 2, int c = 3)
    {
        this.a = a;
        this.b = b;
        this.c = c;
    }
}

所有参数都是可选的,以便用户可以使用

实例化类
Test test = new Test(a:a, c:c);

或者用户选择的任何内容,而不必传递所有或甚至任何参数。

现在说我们要添加另一个可选参数StreamWriter sw = new StreamWriter(File.Create(@"app.log"));(我假设这是实例化StreamWriter类的正确语法)。

显然,作为一个必要的争论,我可以将其添加到构造函数中,如下所示:

public Test(StreamWriter sw, int a = 1, int b = 2, int c = 3)

但如果我希望它成为可选参数,我该怎么办?以下内容:

public Test(int a = 1, int b = 2, int c = 3, StreamWriter sw = new StreamWriter(File.Create(@"app.log")))

如果您收到以下错误,则不是选项:

"Default parameter value for 'sw' must be a compile-time constant"

我是否有另一种方法可以使sw成为可选参数而不会收到此错误?

3 个答案:

答案 0 :(得分:2)

无法使用可选参数。您将需要使用重载:

public Test(int a = 1, int b = 2, int c = 3)
    : this(new StreamWriter(File.Create(@"app.log")), a, b, c)
{
}

public Test(StreamWriter sw, int a = 1, int b = 2, int c = 3)

答案 1 :(得分:0)

您不能放置必须在运行时评估的表达式。

您可以做的一件事是传入null,您的函数可以检测并替换该表达式。如果它不为null,则可以按原样使用。

答案 2 :(得分:0)

使默认值为null并在构造函数体中检查null。

public Test(int a = 1, int b = 2, int c = 3, StreamWriter sw = null)    
{
    if (sw == null)
        sw = new StreamWriter(File.Create(@"app.log"));

    this.a = a;
    this.b = b;
    this.c = c;
}