简体   繁体   English

如何在C#中根据参数在命令行或文件中输出字符串?

[英]How to output string on command line or in a file, depending on a parameter, in C#?

How to output string on command line or in a file, depending on a parameter, in C#? 如何在C#中根据参数在命令行或文件中输出字符串?

I have parameter: 我有参数:

bool console = true; // or false

then I have some code that creates a StringBuilder. 然后我有一些代码创建一个StringBuilder。 I want to output to either Console or to a StreamWriter, based on the console variable. 我想基于console变量输出到Console或StreamWriter。

The tricky part is: 棘手的部分是:

  1. I need to write in small pieces, not a whole string at a time 我需要写成小块,而不是一次写完整的字符串
  2. Given 1) I will end up with code like: 给定1)我最终将得到如下代码:

     if (console ) { Console.WriteLine(someString); } else { using (StreamWriter writer = new StreamWriter(file)) { writer.WriteLine(someString); } } 

every single time I need to add to the string! 每一次我都需要添加到字符串中!

So how do I escape this code bloat? 那么,如何避免此代码膨胀?

You do not need to create an interface yourself; 您无需自己创建接口; you can simply change your code to take a TextWriter as an input: 您可以简单地更改代码以将TextWriter作为输入:

private void DoSomethingAndWriteLog(TextWriter writer)
{
    // Do something
    var someString = "Test";
    writer.WriteLine(someString);
}

Then you can call this method both using Console. 然后,您都可以使用控制台调用此方法。 Out and a custom TextWriter: 一个自定义的TextWriter:

if (console)
{
    DoSomethingAndWriteLog(Console.Out);
} 
else 
{
    using (StreamWriter writer = new StreamWriter(file)) 
    {
        DoSomethingAndWriteToLog(writer);
    }
}

As a generalized case, you define an output writer interface, 一般而言,您可以定义一个输出编写器接口,

interface IOutputWriter
{
    void WriteLine(string s);
}

then write 2 classes that conform to that interface, and inject the appropriate one into your code. 然后编写符合该接口的2个类,并将适当的一个注入到您的代码中。

void YourCode (IOutputWriter writer)
{ 
     // ...
     writer.WriteLine(output);
}

void Main()
{
    IOutputWriter writer;
    if (console)
    { 
        writer = new ConsoleWriter();
    }
    else
    { 
        writer = new StreamWriter();
    }
    YourCode (writer);

}

You can then later define new implementations of IOutputWriter to cope with new requirements (eg: PrinterWriter, DatabaseWriter, etc). 然后,您以后可以定义IOutputWriter新实现来满足新的要求(例如:PrinterWriter,DatabaseWriter等)。

You can make Console.WriteLine output to file, by invoking Console.SetOut and passing a StreamWriter as a parameter: 您可以通过调用Console.SetOut并将StreamWriter作为参数来将Console.WriteLine输出到文件。

if (needToOutputToFile)
{
    Console.SetOut (streamWriter);
}
Console.WriteLine ("This is written in a file, if needToOutputToFile is true");

You can try using Console.Out standard writer and trenary operator : 您可以尝试使用Console.Out标准编写器三元运算符

  using (TextWriter writer = console ? Console.Out : new StreamWriter(file)) {
    ...
    writer.WriteLine(someString);
    ...
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM