可以重载Console.ReadLine吗?(或任何静态类方法)

com*_*cme 4 c# console static overloading class

我正在尝试创建一个System.Console.ReadLine()带有字符串参数的方法的重载.我的意图基本上是能够写作

string s = Console.ReadLine("Please enter a number: ");
Run Code Online (Sandbox Code Playgroud)

代替

Console.Write("Please enter a number: ");
string s = Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)

我不认为有可能重载Console.ReadLine自己,所以我尝试实现一个继承的类,如下所示:

public static class MyConsole : System.Console
{
    public static string ReadLine(string s)
    {
        Write(s);
        return ReadLine();
    }
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为它不可能继承System.Console(因为它是一个自动生成的静态类是一个密封的类).

我想在这里做什么才有意义?或者想要从静态类中重载某些东西永远不是一个好主意?

Fre*_*örk 6

只需将控制台包装在您自己的类中,然后使用它.你不需要为此继承:

class MyConsole
{
    public static string ReadLine()
    {
        return System.Console.ReadLine();
    }
    public static string ReadLine(string message)
    {
        System.Console.WriteLine(message);
        return ReadLine();
    }
    // add whatever other methods you need
}
Run Code Online (Sandbox Code Playgroud)

然后你可以继续在你的程序中使用那个:

string whatEver = MyConsole.ReadLine("Type something useful:");
Run Code Online (Sandbox Code Playgroud)

如果您希望进一步提高它并使其MyConsole更加灵活,您还可以添加支持来替换输入/输出实现:

class MyConsole
{
    private static TextReader reader = System.Console.In;
    private static TextWriter writer = System.Console.Out;

    public static void SetReader(TextReader reader)
    {
        if (reader == null)
        {
            throw new ArgumentNullException("reader");
        }
        MyConsole.reader = reader;
    }

    public static void SetWriter(TextWriter writer)
    {
        if (writer == null)
        {
            throw new ArgumentNullException("writer");
        }
        MyConsole.writer = writer;
    }


    public static string ReadLine()
    {
        return reader.ReadLine();
    }
    public static string ReadLine(string message)
    {

        writer.WriteLine(message);
        return ReadLine();
    }
    // and so on
}
Run Code Online (Sandbox Code Playgroud)

这将允许您从任何TextReader实现驱动程序,因此命令可以来自文件而不是控制台,这可以提供一些不错的自动化方案......

更新
您需要公开的大多数方法都非常简单.好吧,或许写起来有点乏味,但这不是很多分钟的工作,你只需要做一次.

示例(假设我们在上面的第二个示例中,带有可分配的读者和编写者):

public static void WriteLine()
{
    writer.WriteLine();
}

public static void WriteLine(string text)
{
    writer.WriteLine(text);
}

public static void WriteLine(string format, params object args)
{
    writer.WriteLine(format, args);
}
Run Code Online (Sandbox Code Playgroud)