2010-12-22 56 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

相關問題