如何为Console.WriteLine覆盖使用自己的类? [英] How can I use an own class for Console.WriteLine override?

查看:99
本文介绍了如何为Console.WriteLine覆盖使用自己的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的ConsoleEngine类处理Console.WriteLine()方法.如何准备我的ConsoleEngine类以覆盖WriteLine()方法?

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?

推荐答案

您可以创建一个从TextWriter派生的类:

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;
        }
    }
}

并将Console输出设置为该类的实例:

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

Console.SetOut(new MyWriter());

这篇关于如何为Console.WriteLine覆盖使用自己的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆