只需將控制檯包裝在自己的類中,然後使用它。你並不需要繼承爲:
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);
}
難道你們就不能只是創建自己的靜態類,只是工作在控制檯上? – 2010-12-22 09:52:36