编写高质量Dart程序-字符串的使用

以下是在Dart中编写字符串时需要记住的一些最佳实践。

使用相邻字符串连接字符串文字。

如果有两个字符串字面值(不是值,而是实际引用的字面值),则不需要使用+连接它们。就像在C和c++中,简单地把它们放在一起就能做到。这是创建一个长字符串很好的方法但是不适用于单独一行。

raiseAlarm(
'ERROR: Parts of the spaceship are on fire. Other '
'parts are overrun by martians. Unclear which are which.');

以下是错误示例:

raiseAlarm('ERROR: Parts of the spaceship are on fire. Other ' +
'parts are overrun by martians. Unclear which are which.');

优先使用插值来组合字符串和值。

如果您之前是用其他语言做开发的,那么您习惯使用+的长链来构建文字和其他值的字符串。 这在Dart中有效,但使用插值总是更清晰,更简短:

'Hello, $name! You are ${year - birth} years old.';

以下是不推荐的写法:

'Hello, ' + name + '! You are ' + (year - birth).toString() + ' y...';

在不需要时,避免在插值中使用花括号。

如果您正在插入一个简单的标识符,而后面没有紧跟更多的字母数字文本,那么{}应该被省略。

'Hi, $name!'
"Wear your wildest $decade's outfit."
'Wear your wildest ${decade}s outfit.'

要避免以下的写法:

'Hi, ${name}!'
"Wear your wildest ${decade}'s outfit."

猜你喜欢

转载自blog.csdn.net/hayixia606/article/details/81781981