基于变量值的动态方法调度
长的 switch 语句常常会让人不悦。解决方案是使用多态性。但是,如果我打开的不是类型代码怎么办?我想做的是将 switch 语句替换为类似的内容...
public void HandleString(string s = "Hello")
{
...
}
public void HandleString(string s = "Goodbye")
{
...
}
...
HandleString("Hello"); // results in the first method being called.
这将替换以下内容...
string s = "Hello";
switch(s)
{
case "Hello":
...
break;
case "Goodbye":
...
break;
default;
break;
}
有什么想法吗?理论上,我认为您可以完全取消“if/switch”语句,而只调用根据表达式的值自动绑定的方法。
Long switch statments are often frowned upon. The solution is to use polymorphism. However what if the thing I'm switching on is not a type code? What I would like to do is replace the switch statement with something like this...
public void HandleString(string s = "Hello")
{
...
}
public void HandleString(string s = "Goodbye")
{
...
}
...
HandleString("Hello"); // results in the first method being called.
This would replace the following...
string s = "Hello";
switch(s)
{
case "Hello":
...
break;
case "Goodbye":
...
break;
default;
break;
}
Any ideas? In theory I think you could do away with 'if/switch' statements altogether and just call methods that are automatically bound based on the value of an expression.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您有大量选项,并且将来很有可能会有更多选项 - 或者您只需要系统易于扩展 - 那么您始终可以使用显式调度表:
您还可以提供一种扩展方法通过允许 API 的外部客户端为给定字符串注册自己的处理程序来创建表。
If you have a large number of options, and high possibility that there will be more in the future - or you just need to system to be easily extensible - then you can always use an explicit dispatch table:
You can also provide a way to extend the table by allowing external clients of your API to register their own handler for a given string.
有些语言实现了这种语义。我熟悉的一个是来自 Phillips 的名为 Elegant 的编译器生成工具。
在这样的语言中,简单的阶乘算法可能如下所示:
There are languages that implement that sort of semantics. One that I'm familiar with is the compiler generator tool called Elegant from Phillips.
In a language like this, a simple factorial algorithm might look like: