Dart 3 中匹配类型的推荐语法是什么?

huangapple go评论56阅读模式
英文:

What's the recommended syntax for matching types in Dart 3?

问题

Dart 3有两种匹配类型的语法:

switch(myObject) {
  case TypeA(): // 使用参数解构
  case TypeB _: // 不使用参数解构
}

如果不需要进一步解构,应该使用哪种?其中一种性能更高吗?

英文:

Dart 3 has two syntaxes for matching types:

switch(myObject) {
  case TypeA(): // With parameter destructuring
  case TypeB _: // Without parameter destructuring
}

If no further destructuring is needed, which should be used? Is one more performant than the other?

答案1

得分: 3

我建议使用case TypeB _: 作为编写仅执行类型测试的一般方式。

原因是它允许任何类型语法,而TypeA()只允许类型名称,因此如果您需要匹配函数,可以直接编写:

  case void Function() _: .... // 可行

您也可以对任何类型使用(),只需使用辅助类型别名,以便类型具有正确的格式:

typedef typeof<T> = T;
// ...
  case typeof<void Function()>(): ... // 也可行
英文:

I'll recommend case TypeB _: as the general way to write type tests that do nothing else.

The reason is that it allows any type syntax, where TypeA() only allow type names, so if you ever need to match a function, you can write it directly as:

  case void Function() _: .... // Works

You can use () for any type as well, you just need a helper type alias, so the type has the correct format:

typedef typeof<T> = T;
// ...
  case typeof<void Function()>(): ... // Works too.

huangapple
  • 本文由 发表于 2023年6月25日 19:35:14
  • 转载请务必保留本文链接:https://go.coder-hub.com/76550196.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定