enum 与string的转换

从enum转换为string可以用ToString()方法,如果从string转化为enum:

var domInt = Convert.ToString(row["DomInt"]);
FlightDomInt domIntEnum = (FlightDomInt)Enum.Parse(typeof(FlightDomInt), domInt);

var aCSeries = Convert.ToString(row["ACSeries"]);
AirCraftType aCSeriesEnum = (AirCraftType)Enum.Parse(typeof(AirCraftType), aCSeries);

在 C++ 中,将枚举类型(`enum`)的值转换为字符串类型(`std::string`)通常需要手动实现,因为 C++ 标准库并未提供直接支持。枚举类型的值本质上是整数类型,因此可以通过将枚举值映射到对应的字符串来实现转换。 ### 使用 `switch` 语句进行映射 可以通过 `switch` 语句将枚举值显式映射为字符串。例如: ```cpp enum class Color { Red, Green, Blue }; std::string color_to_string(Color color) { switch (color) { case Color::Red: return "Red"; case Color::Green: return "Green"; case Color::Blue: return "Blue"; default: return "Unknown"; } } ``` 这种方法适用于枚举值有限且可以明确列出的情况,并且可以确保每个枚举值都有对应的字符串表示[^4]。 ### 使用 `std::map` 或 `std::unordered_map` 进行映射 另一种常见做法是使用 `std::map` 或 `std::unordered_map` 将枚举值字符串进行关联。例如: ```cpp #include <unordered_map> #include <string> enum class Color { Red, Green, Blue }; const std::unordered_map<Color, std::string> color_map = { {Color::Red, "Red"}, {Color::Green, "Green"}, {Color::Blue, "Blue"} }; std::string color_to_string(Color color) { auto it = color_map.find(color); if (it != color_map.end()) { return it->second; } return "Unknown"; } ``` 这种方式结构清晰,便于维护和扩展,尤其适用于枚举值较多的情况。 ### 使用模板函数提高复用性 可以将上述逻辑封装为模板函数,以提高代码复用性。例如: ```cpp template <typename T> std::string enum_to_string(T value) { static const std::unordered_map<T, std::string> mapping = { {static_cast<T>(0), "Red"}, {static_cast<T>(1), "Green"}, {static_cast<T>(2), "Blue"} }; auto it = mapping.find(value); return it != mapping.end() ? it->second : "Unknown"; } ``` 这种方式适用于需要统一处理多个枚举类型的情况,同时保持代码简洁和一致性。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值