我要上一节文言文课。这就是:
enum{
us,
uk,
in,
}这门课把我的国家代码保存在上面。但是在vscode中显示了这样的信息:
'in' can't be used as an identifier because it's a keyword.
Try renaming this to be an identifier that isn't a keyword.我想和其他人一样用这个。我要用那个枚举类来处理Api请求。那门课我怎么用"in“呢?
发布于 2022-08-11 12:43:41
发布于 2022-08-11 13:00:14
我的建议是在你的名字里用整个国家的名字
enum Country{
none,
usa,
unitedKingdoms,
india,
}而不是密码。这也使得那些不知道所有代码的人在编程时更容易。
要将它传递到API中(大概是作为字符串),可以使用扩展方法(pre 2.17 aproach,详见下文)。
extension CountryFunctionalities on Country{
String get asCountryCode {
switch (this) {
case Country.usa: return "us";
case Country.unitedKingdoms: return "uk";
case Country.india: return "in";
default: return "";
}
}
}然后把它当作
Country countryInstance = Country.india;
print(countryInstance.asCountryCode); // output: "in"如果使用Dart 2.17或更高版本,则可以使用增强枚举(感谢建议编辑的@venir )。您可以在@Hannes回答如下中看到它的应用,也可以在迈克尔·汤姆森的博客文章"Dart 2.17:生产力与整合“的标题“增强的成员枚举”下阅读更多有关它的内容。
或者,您可以使用Alpha-3代码"IND“安装Alpha-2代码"IN”。https://www.iban.com/country-codes
最后,您可以简单地使用"IN“而不是"in”作为名称,而不是保留关键字。
发布于 2022-08-11 13:25:25
除哈雷金虎外:
Flutter 3也支持这样编写枚举:
enum Country {
usa('us'),
unitedKingdoms('uk'),
india('in');
const Country(this.cc);
final String cc;
}
final String cc = Country.uk.cc;https://stackoverflow.com/questions/73320794
复制相似问题