简体   繁体   English

流处理:打印功能C#

[英]Stream handling: print function c#

I am relatively new to C#, and have a question regarding output streams. 我是C#的新手,对输出流有疑问。

In my current program I have a class named "batches", which contains some data (batch id, startTime, endTime, duration, etc). 在当前程序中,我有一个名为“批处理”的类,其中包含一些数据(批处理ID,startTime,endTime,duration等)。 I have a list of batches, and would like to be able to print each batch both to the console, and to a file. 我有一个批次列表,并且希望能够将每个批次都打印到控制台和文件中。

I tried to achieve this by writing a Print() method inside of my batch class which prints everything neatly. 我试图通过在我的批处理类中编写一个Print()方法来实现此目的,该方法可以整齐地打印所有内容。 I would like to pass as an argument to this function either the console or the output file (let's call it fout) so that the function can write to either one. 我想将控制台或输出文件(我们称为fout)作为该函数的参数传递,以便该函数可以写入其中一个。 Since both Console and fout use the WriteLine() method like this: 由于Console和fout都使用WriteLine()方法,如下所示:

Console.WriteLine("Some text");
fout.WriteLine("Some text");

it seemed like I should give my print function a parameter of type StreamWriter so that I could pass to it either Console or fout, and achieve the same goal as above like this: 似乎我应该给我的打印函数一个类型为StreamWriter的参数,以便我可以将它传递给Console或fout,并实现与上述相同的目标,如下所示:

Print(Console);
Print(fout);

void Print(StreamWriter stream) {
    stream.WriteLine($"Batch ID: {Id}");
    ...
    ...
}

However, when I try passing console to my print function, I receive an error. 但是,当我尝试将控制台传递给我的打印功能时,出现错误。 I am not familiar enough with streams or how the console works or the inheritance tree which would allow both fout and Console to both be able to use the WriteLine function, but not my print function. 我对流或控制台的工作方式或继承树还不太熟悉,继承树不允许fout和Console都可以使用WriteLine函数,但不能使用我的打印函数。 Perhaps I just need a different type as a parameter in my function, but I do not know what that type would be. 也许我只需要在函数中使用其他类型作为参数,但是我不知道该类型是什么。

I am most comfortable programming in c++, and I know that if I were working with that language, it would make most sense to overload the ostream operator; 我最喜欢用c ++进行编程,并且我知道如果我使用该语言,则重载ostream运算符是最有意义的。 basically, I want a print function that would behave as an ostream operator would. 基本上,我想要一个可以像ostream运算符一样运行的打印函数。

If anyone needs me to answer any clarifying questions, please let me know and I can do that right away. 如果有人需要我回答任何澄清的问题,请让我知道,我可以立即进行。 Thanks in advance! 提前致谢!

What you are looking for is a interface , create an ILogger , provide implementation and pass it to your print method. 您正在寻找的是一个interface ,创建一个ILogger ,提供实现并将其传递给您的打印方法。 This way, if you want to control the printing logic based on conditions, it would be easy. 这样,如果您想根据条件控制打印逻辑,那将很容易。

static void Main(string[] args)
{
    Batch batch = new Batch() { ID = 1, StartTime = DateTime.Now, EndTime = DateTime.Now, Duration = 10 };

    batch.Print(new ConsoleLogger(), new FileLogger());
}

public class Batch
{
    public int ID { set; get; }
    public DateTime StartTime { set; get; }
    public DateTime EndTime { set; get; }
    public double Duration { set; get; }

    public void Print(ILogger logger)
    {
        logger.Log(this.ToString());
    }

    public void Print(params ILogger[] loggers)
    {
        foreach (ILogger logger in loggers)
        {
            Print(logger);
        }
    }

    public override string ToString()
    {
        return $"ID = {ID} ** StartTime = {StartTime} ** EndTime = {EndTime} ** Duration = {Duration}";
    }
}

public interface ILogger
{
    void Log(string text);
}

public class ConsoleLogger : ILogger
{
    public void Log(string text)
    {
        Console.WriteLine(text);
    }
}

public class FileLogger : ILogger
{
    string filePath = "log.txt";

    public void Log(string text)
    {
        File.AppendAllText(filePath, text + Environment.NewLine);
    }
}

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

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