可以重载 Console.ReadLine 吗? (或任何静态类方法)
我正在尝试创建 System.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 继承(因为它是一个静态类,会自动成为一个密封类)。
我在这里尝试做的事情有意义吗?或者从静态类中重载某些东西从来都不是一个好主意?
I'm trying to create an overload of the System.Console.ReadLine()
method that will take a string argument. My intention basically is to be able to write
string s = Console.ReadLine("Please enter a number: ");
in stead of
Console.Write("Please enter a number: ");
string s = Console.ReadLine();
I don't think it is possible to overload Console.ReadLine
itself, so I tried implementing an inherited class, like this:
public static class MyConsole : System.Console
{
public static string ReadLine(string s)
{
Write(s);
return ReadLine();
}
}
That doesn't work though, cause it is not possible to inherit from System.Console
(because it is a static class which automatically makes is a sealed class).
Does it make sense what I'm trying to do here? Or is it never a good idea to want to overload something from a static class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只需将控制台包装在您自己的类中并使用它即可。您不需要为此继承:
然后您可以继续并在您的程序中使用它:
如果您希望进一步推动它并使
MyConsole
更加灵活,您可以还添加对替换输入/输出实现的支持:这将允许您从任何 TextReader 实现驱动程序,因此命令可以来自文件而不是控制台,这可以提供一些不错的自动化场景...
更新
您需要公开的大多数方法都非常简单。好吧,写起来可能有点乏味,但这不需要很多分钟的工作,而且你只需要做一次。
示例(假设我们在上面的第二个示例中,具有可分配的读取器和写入器):
Just wrap the console in your own class and use that instead. You don't need to inherit for that:
Then you can go ahead and use that one in your program instead:
If you wish to push it a bit further and make
MyConsole
a bit more flexible, you could also add support to replace the input/output implementations:This would allow you to drive the program from any
TextReader
implementation, so commands could come from a file instead of the console, which could provide some nice automation scenarios...Update
Most of the methods that you need to expose are extremely simple. OK, a bit tedious to write perhaps, but it's not many minutes of work, and you need to do it only once.
Example (assuming we are in my second sample above, with assignable reader and writer):