在没有编译时间常数错误的情况下,将类作为另一类构造函数中的可选参数传递
本文关键字:一类 构造函数 参数传递 时间常数 编译 错误 情况下 | 更新日期: 2023-09-27 18:22:31
在这个例子中,假设我们有一个类:
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
成为可选参数而不会收到此错误?
没有可选参数。您需要为此使用过载:
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)
不能在其中放入必须在运行时求值的表达式。
您可以做的一件事是传入null,您的函数可以检测null并用该表达式替换它。如果它不为null,则可以按原样使用。
将默认值设为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;
}