C# 中运行时确定的切换值
我有一个 c# 中的 case 语句。 我想在运行时从配置文件中选择案例的值。 这可能吗?
I've got a case statement in c#. I would like to chose the values for the cases from a configuration file at run time. Is this possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不使用 switch 语句,不。 case 标签必须是编译时常量。
Marc Gravell 有一个类似开关的结构,你可以在某个地方使用......我会尽力找到它。 但它可能不适合您的特定用途。
否则,一系列 if/else if/else if [...] /else 是可行的方法。
Not with a switch statement, no. The case labels have to be compile-time constants.
Marc Gravell has a switch-like construct you could use, somewhere... I'll try to find it. It may well not be suitable for your particular usage though.
Otherwise, a sequence of if/else if/else if [...] /else is the way to go.
由于 C# 中 case 语句中使用的值预计是常量,我认为不可能在运行时从配置文件设置这些值。
As the values being used in a case statement in C# are expected to be constants I don't think it is possible to set these at runtime from a config file.
正如其他人所说, switch 语句需要编译时的值,因为底层哈希表是在编译时构建的。 如果您有在运行时确定的条目,如果我是您,我会使用带有命令模式或委托的哈希表/字典。
As others have said, the switch statement needs the values at compile time since the underlying hash table is built at compile time. If you have entries that are determined at runtime, I would use hash tables / dictionaries with command pattern or delegates if I were you.