Perhaps overloading Console.ReadLine? (or any method of a static class)

I am trying to create an overload of a method System.Console.ReadLine()that will take a string argument. My intention is basically to write

string s = Console.ReadLine("Please enter a number: ");

instead

Console.Write("Please enter a number: ");
string s = Console.ReadLine();

I don’t think that you can overload it Console.ReadLineyourself, so I tried to implement an inherited class, for example:

public static class MyConsole : System.Console
{
    public static string ReadLine(string s)
    {
        Write(s);
        return ReadLine();
    }
}

This does not work because it is impossible to inherit from System.Console(because it is a static class that automatically creates a private class).

Does what I am trying to do here make sense? Or is it worth it to overload something from a static class?

+3
source share
1 answer

. :

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
}

:

string whatEver = MyConsole.ReadLine("Type something useful:");

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
}

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);
}
+6

Source: https://habr.com/ru/post/1781629/


All Articles