只需将控制台包装在自己的类中,然后使用它。你并不需要继承为:
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