这就是我想要做的事情:
XmlWriter writer = XmlWriter.Create(
(string.IsNullOrEmpty(outfile) ? Console.Out : outfile)
);
Run Code Online (Sandbox Code Playgroud)
但是,这不会编译,因为"System.IO.TextWriter"和"string"之间没有隐式转换,因此无法确定错误"条件表达式的类型".以上代码简化了以下内容:
XmlWriter writer;
if (string.IsNullOrEmpty(outfile))
{
writer = XmlWriter.Create(Console.Out); // Constructor takes TextWriter
}
else
{
writer = XmlWriter.Create(outfile); // Constructor takes string
}
Run Code Online (Sandbox Code Playgroud)
这两个调用Create完全有效,并编译.有没有办法使这个更紧凑,就像我试图用我的内联测试?
对我来说,我想要的东西不起作用是没有意义的.通过这种思考,似乎编译器会评估string.IsNullOrEmpty(outfile)以确定采取哪种情况:
Console.Out,然后看到它需要以多态方式选择XmlWriter.Create带有TextWriter 的版本.outfile,然后看到它需要以多态方式选择XmlWriter.Create带有字符串的版本.ML编程是否扭曲了我的大脑?
Lee*_*Lee 18
你不能这样做的原因是因为编译器必须选择在编译时使用哪个Create重载 - 你的方法需要在运行时完成.你可以做的最短的可能是:
XmlWriter writer = String.IsNullOrEmpty(outfile)
? XmlWriter.Create(Console.Out)
: XmlWriter.Create(outfile);
Run Code Online (Sandbox Code Playgroud)
每个人似乎都建议如下:
XmlWriter writer = String.IsNullOrEmpty(outfile)
? XmlWriter.Create(Console.Out)
: XmlWriter.Create(outfile);
Run Code Online (Sandbox Code Playgroud)
但是,这也是可行的:
XmlWriter writer = XmlWriter.Create(string.IsNullOrEmpty(outfile)
? Console.Out : new StreamWriter(outfile));
Run Code Online (Sandbox Code Playgroud)
后者更接近你原来的尝试,IMO更紧凑.