2010-12-22 68 views
3

我试图创建一个System.Console.ReadLine()方法的重载将采取字符串参数。我的目的主要是为了能够写出重载Console.ReadLine可能吗? (或任何静态类方法)

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

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

代替我不认为这是可能超载Console.ReadLine本身,所以我想实现继承的类,如下所示:

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

这并不工作,虽然,因为它是不可能从System.Console继承(因为它是一个静态类,它会自动为一个密封的类)。

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

+1

难道你们就不能只是创建自己的静态类,只是工作在控制台上? – 2010-12-22 09:52:36

回答

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 
} 

然后你就可以继续使用一个在你的程序,而不是:

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 implemen驱动程序塔季翁,所以命令可能来自文件而不是控制台,它可以提供一些不错的自动化情景......

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

实例(假设我们是我的第二个样本以上,具有分配的读者和作家):

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

如果我这样做,我不得不记得为`ReadlLine()`使用`MyConsole`,但是对于任何其他Console方法使用`Console`。如果继承是可能的,我可以使用`MyConsole.WriteLine()`,`MyConsole.Clear()`或任何其他`Console`方法。 – comecme 2010-12-22 09:52:58

相关问题