C#枚举(一)使用总结以及扩展类分享

定义枚举
枚举并不显式从继承 Enum ; 继承关系由编译器隐式处理

// 枚举YesOrNo
public enum YesOrNo
{
[Description("")]
None = 0,
[Description(“是”)]
Yes = 1,
[Description(“否”)]
No = 2
}

// 枚举YesOrNo 基础类型为byte
public enum YesOrNo_Byte : byte
{
[Description("")]
None = 0,
[Description(“是”)]
Yes = 1,
[Description(“否”)]
No = 2
}
枚举 => 转字符串
string yesString = YesOrNo.Yes.ToString(); // Yes
枚举 => 转数字
int yesInt = (int)YesOrNo.Yes; // 1
字符串 => 枚举
YesOrNo yesOrNo_Yes = (YesOrNo)Enum.Parse(typeof(YesOrNo), “Yes”); // YesOrNo.Yes
数字 => 枚举
YesOrNo yesOrNo_No = (YesOrNo)2; // YesOrNo.No
获取所有的枚举成员
Array yesOrNos = Enum.GetValues(typeof(YesOrNo)); // [YesOrNo.None,YesOrNo.Yes,YesOrNo.No]
获取所有枚举成员的属性名
string[] yesOrNoNames = Enum.GetNames(typeof(YesOrNo)); // [“None”,“Yes”,“No”]
获取枚的举基础类型
Type typeInt = Enum.GetUnderlyingType(typeof(YesOrNo)); // System.Int32

Type typeByte = Enum.GetUnderlyingType(typeof(YesOrNo_Byte)); // System.Byte
扩展方法
字符串 => 转枚举
// GetEnum() 字符串 => 转枚举
var yesString = “Yes”.GetEnum(); // YesOrNo.Yes

///
/// 根据字符串转成指定枚举值
///
public static T GetEnum(this string enumString)
{
return (T)Enum.Parse(typeof(T), enumString);
}
枚举 => 转数字
// GetIntValue() 枚举 => 转数字
int yesInt = YesOrNo.Yes.GetIntValue(); // 1

///
/// 获取枚举的值
///
public static int GetIntValue(this Enum value)
{
return Convert.ToInt32(value);
}
获取枚举的描述
// GetDescription() 获取枚举的描述
var description = YesOrNo.Yes.GetDescription(); // 是

///
/// 根据枚举获取枚举描述
///
public static string GetDescription(this Enum value)
{
var field = value.GetType().GetField(value.ToString());
var customAttribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
if (customAttribute == null)
return value.ToString();
else
return ((DescriptionAttribute)customAttribute).Description;
}
将枚举字符串值与描述转字典
// GetEnumDescriptions() 获取枚举字符串值与描述
var dictionary = typeof(YesOrNo).GetEnumDescriptions(); // {{[None, “”]},{[Yes, 是]},{[No, 否]}}

///
/// 获取枚举字符串值及描述值的字典
///

public static IDictionary<string, string> GetEnumDescriptions(this Type enumType)
{
var dictionary = new Dictionary<string, string>();
foreach (Enum code in Enum.GetValues(enumType))
dictionary.Add(code.ToString(), code.GetDescription());

return dictionary;

}
将枚举值与描述转字典
// GetEnumIntDescriptions() 获取枚举值与描述
var intDictionary = typeof(YesOrNo).GetEnumIntDescriptions(); // {{[0, “”]},{[1, 是]},{[2, 否]}}

///
/// 获取枚举值及描述值的字典
///

public static IDictionary<int, string> GetEnumIntDescriptions(this Type enumType)
{
var dictionary = new Dictionary<int, string>();
foreach (Enum code in Enum.GetValues(enumType))
dictionary.Add(code.GetIntValue(), code.GetDescription());

return dictionary;

}
USB Microphone https://www.soft-voice.com/
Wooden Speakers https://www.zeshuiplatform.com/
亚马逊测评 www.yisuping.cn
深圳网站建设www.sz886.com

上一篇:你真的知道typeof null的结果为什么是‘object‘吗?


下一篇:STM32-按键输入