Enum转string
时间: 2023-09-04 22:08:02 浏览: 79
将一个枚举类型的值转换为字符串类型可以通过以下两种方式实现:
1. 使用枚举类型的ToString()方法
每个枚举类型都有一个ToString()方法,可以将枚举值转换为对应的字符串。例如:
```
enum WeekDay { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
WeekDay day = WeekDay.Monday;
string dayString = day.ToString(); // "Monday"
```
2. 使用类型转换操作符
可以使用类型转换操作符将枚举值转换为int类型,然后将int类型转换为字符串类型。例如:
```
enum WeekDay { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
WeekDay day = WeekDay.Monday;
string dayString = ((int)day).ToString(); // "0"
```
需要注意的是,如果枚举类型定义了字符串常量,可以使用字符串常量来表示枚举值,例如:
```
enum WeekDay { Monday = 1, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday };
WeekDay day = WeekDay.Monday;
string dayString = day.ToString(); // "Monday"
WeekDay friday = WeekDay.Friday;
string fridayString = friday.ToString(); // "Friday"
WeekDay saturday = WeekDay.Saturday;
string saturdayString = saturday.ToString(); // "Saturday"
```
阅读全文