Pass Class as Optional Parameter Within a Another Class Constructor Without Compile-Time Constant Error

StackOverflow https://stackoverflow.com/questions/17683034

Вопрос

In this example assume we have a class:

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;
    }
}

All parameters are optional so that the user can instantiate the class using either

Test test = new Test(a:a, c:c);

Or whatever the user chooses without having to pass all or even any parameters.

Now say we want to add another optional parameter StreamWriter sw = new StreamWriter(File.Create(@"app.log")); (I assume this is correct syntax for instantiating the StreamWriter class).

Obviously as a required arguement I can add it to the constructor like so:

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

But what should I do if I want it to be an optional parameter? The following:

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

Isn't an option as you receive the following error:

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

Is there another way I can make sw an optional parameter without receiving this error?

Это было полезно?

Решение

There is no way with optional parameters. You will need to use an overload for this:

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)

Другие советы

You can't put an expression that must be evaluated at run-time in there.

One thing you could do is pass in null, which your function can detect and replace with that expression. If it's not null, it can just be used as-is.

Make the default value null and check for null within the constructor body.

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;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top