How can I use an own class for Console.WriteLine override?

浪子不回头ぞ 提交于 2019-12-01 20:11:39

问题


I want my ConsoleEngine class to handle the Console.WriteLine() Method. How do I have to prepare my ConsoleEngine class to override the WriteLine() method?


回答1:


You can create a class that derives from TextWriter:

public class MyWriter : TextWriter
{
    public override void Write(char value)
    {
        //Do something, like write to a file or something
    }

    public override void Write(string value)
    {
        //Do something, like write to a file or something
    }

    public override Encoding Encoding
    {
        get 
        {
            return Encoding.ASCII;
        }
    }
}

and set the Console output to an instance of that class:

Console.SetOut(new MyWriter());


来源:https://stackoverflow.com/questions/32661000/how-can-i-use-an-own-class-for-console-writeline-override

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!