很多 if else if 的 dart 替代品
Posted
技术标签:
【中文标题】很多 if else if 的 dart 替代品【英文标题】:dart alternate for a lot of if elseiif 【发布时间】:2019-12-06 12:44:01 【问题描述】:我想用另一个字符串替换 Dart 中的 URL 字符串。 示例:
if (url == "http://www.example.com/1")
home = "example";
else if (url == "http://www.example.com/2")
home = "another example";
难道没有更好的方法,代码更少,速度更快吗?我必须这样做超过 60 次..
【问题讨论】:
“更好的方法”高度基于意见。在什么方面更好?可读性?可维护性 ?速度? 如果有更好的方法,尤其是在更少的代码中 好吧,你的第二个案例可以完全删除,因为它的条件永远不会是真的...... 这只是一个错字。当然最后会有另一个数字。 【参考方案1】:我喜欢 Muldec 的回答,因为我个人觉得 switch 语句读起来有点尴尬。我也喜欢有一个默认选项,这样你就可以“有点”重新定义 switch 语句。额外的好处是您可以将它内联用作表达式,并且它仍然是类型安全的......就像这样。
case2(myInputValue,
"http://www.example.com/1": "example",
"http://www.example.com/2": "another example",
"http://www.example.com/3": "yet another one",
, "www.google");
case2 代码可以是
TValue case2<TOptionType, TValue>(
TOptionType selectedOption,
Map<TOptionType, TValue> branches, [
TValue defaultValue = null,
])
if (!branches.containsKey(selectedOption))
return defaultValue;
return branches[selectedOption];
【讨论】:
【参考方案2】:只需将值“http://www.example.com”存储在字符串变量中并每次连接。参考以下代码
String originalUrl = 'https://www.example.com';
if (url == originalUrl + '/1')
【讨论】:
否则你可以使用 Switch Case【参考方案3】:您可以使用 switch 语句。
switch(variable_expression)
case constant_expr1:
// statements;
break;
case constant_expr2:
//statements;
break;
default:
//statements;
break;
参考文献
Tutorials Point Flutter Dart【讨论】:
【参考方案4】:如果你想要更少的代码,你可以这样做:
homes =
"http://www.example.com/1": "example",
"http://www.example.com/2": "another example",
"http://www.example.com/3": "yet another one",
;
home = homes[url];
【讨论】:
以上是关于很多 if else if 的 dart 替代品的主要内容,如果未能解决你的问题,请参考以下文章