c#通过描述获取枚举名
时间: 2023-08-02 19:16:26 浏览: 55
可以使用Enum.GetName()方法来获取枚举类型中特定值的名称,例如:
```csharp
enum Colors
{
Red,
Green,
Blue
}
Colors color = Colors.Green;
string colorName = Enum.GetName(typeof(Colors), color);
Console.WriteLine(colorName); // 输出 "Green"
```
在此示例中,我们定义了一个名为Colors的枚举类型,它包含三个值:Red、Green和Blue。然后我们将color变量设置为Green,并使用Enum.GetName()方法获取其名称。最后,我们将其输出到控制台上。
相关问题
c#获取枚举以及枚举中的描述
可以使用反射来获取枚举值和描述。具体步骤如下:
1.定义一个枚举类型:
```
public enum Gender
{
[Description("男")]
Male = 1,
[Description("女")]
Female = 2,
}
```
2.通过反射获取枚举值:
```
var genderValues = Enum.GetValues(typeof(Gender));
foreach (var genderValue in genderValues)
{
Console.WriteLine(genderValue); // 输出 Male, Female
}
```
3.通过反射获取枚举值的描述:
```
var genderValues = Enum.GetValues(typeof(Gender));
foreach (var genderValue in genderValues)
{
var fieldInfo = genderValue.GetType().GetField(genderValue.ToString());
var attributes = (DescriptionAttribute[])fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
Console.WriteLine(attributes[0].Description); // 输出 男, 女
}
```
需要注意的是,如果一个枚举值没有描述,则上述代码会抛出异常。可以使用`attributes.Length > 0 ? attributes[0].Description : genderValue.ToString()`来避免异常。
c#将枚举和描述转成数组
可以使用以下代码将C#中的枚举和它们的描述转换为一个数组:
```csharp
public static class EnumHelper
{
public static T[] GetValues<T>()
{
return (T[])Enum.GetValues(typeof(T));
}
public static string[] GetDescriptions<T>()
{
return GetValues<T>()
.Select(e => e.GetDescription())
.ToArray();
}
}
public static class EnumExtensions
{
public static string GetDescription(this Enum value)
{
var field = value.GetType().GetField(value.ToString());
var attribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];
return attribute != null && attribute.Length > 0 ? attribute[0].Description : value.ToString();
}
}
```
其中,`EnumHelper`类包含了两个静态方法:`GetValues`和`GetDescriptions`。`GetValues`方法用于获取枚举的所有值,`GetDescriptions`方法则用于获取枚举的所有描述。
`EnumExtensions`类则扩展了`Enum`类型,实现了获取枚举描述的方法。需要注意的是,这里使用了`DescriptionAttribute`来标记枚举的描述。如果没有使用该特性,则会返回枚举的名称。(如果你没有为枚举添加描述,可以直接返回枚举的名称)
使用示例:
```csharp
public enum MyEnum
{
[Description("描述 1")]
Value1,
[Description("描述 2")]
Value2,
Value3
}
var values = EnumHelper.GetValues<MyEnum>();
var descriptions = EnumHelper.GetDescriptions<MyEnum>();
```