C#实现枚举的相关操作
枚舉中的Descript()描述值,以及枚舉值是一種一一對(duì)應(yīng)的關(guān)系。我們可以獲取其描述值和枚舉值,存放到字典中,
在實(shí)際的使用中我們就可以輕松的根據(jù)枚舉值來(lái)獲取其描述值,也可以通過(guò)枚舉的描述值來(lái)獲取其枚舉值。
根據(jù)枚舉值來(lái)獲取其描述值如下:
??????? /// <summary>
??????? /// 根據(jù)枚舉值來(lái)獲取描述信息
??????? /// </summary>
??????? /// <param name="e">枚舉值</param>
??????? /// <returns></returns>
??????? public static string GetEnumDesc(Enum e)
??????? {
??????????? DescriptionAttribute[] descAttribute = (DescriptionAttribute[])e.GetType().GetField(e.ToString()).GetCustomAttributes(typeof(DescriptionAttribute), false);
??????????? return descAttribute == null || descAttribute.Length == 0 ? string.Empty : descAttribute[0].Description;
??????? }
但是這種方法是比較單一的,只能根據(jù)一個(gè)枚舉值來(lái)獲取一個(gè)描述信息。
以下便可以實(shí)現(xiàn)獲取所有的枚舉值和秒速信息
?/// <summary> ???????
/// 根據(jù)枚舉類型來(lái)獲取枚舉值和枚舉描述信息 ???????
/// </summary> ???????
/// <typeparam name="T"></typeparam> ???????
/// <returns></returns> ???????
public static Dictionary<int, string> GetValueAndDesc<T>() ??????? {
??????????? Dictionary<int, string> dic = new Dictionary<int, string>(); ???????????
try ???????????
{ ???????????????
foreach (FieldInfo item in typeof(T).GetFields()) ???????????????
{ ??????????????????
? if (item.FieldType.IsEnum) ????????????????
??? { ??????????????
????????? int key = (int)typeof(T).InvokeMember(item.Name, BindingFlags.GetField, null, null, null); ???????????????
???????? DescriptionAttribute[] descs = (DescriptionAttribute[])item.GetCustomAttributes(typeof(DescriptionAttribute), false); ????????????
??????????? if (descs.Length > 0 && !dic.ContainsKey(key)) ???????????????
???????? { ?????????????????????????
???????????????? ?? dic.Add(key, descs[0].Description); ???????????????
???????? } ??????????????
????? } ?????????
?????? } ????????
??? } ?????????
?? catch (Exception) ???????
???? { ?????????????? // throw; ??????????? } ??????
????? return dic;
}
這樣之后我們可以輕松的通過(guò)鍵值對(duì)來(lái)輕松的獲取我們先要的值或者描述信息。
?
------------------------哇!我這都三年5個(gè)月的博客齡了,不過(guò)一直沒(méi)有寫博客,希望通過(guò)我們分享,能給有需要的朋友們帶來(lái)幫助--------------
轉(zhuǎn)載于:https://www.cnblogs.com/hglSV/p/BigHGL.html
總結(jié)
以上是生活随笔為你收集整理的C#实现枚举的相关操作的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Mac zsh切换bash bash切换
- 下一篇: [react-native]-React