C#实现枚举的相关操作
枚舉中的Descript()描述值,以及枚舉值是一種一一對應的關系。我們可以獲取其描述值和枚舉值,存放到字典中,
在實際的使用中我們就可以輕松的根據枚舉值來獲取其描述值,也可以通過枚舉的描述值來獲取其枚舉值。
根據枚舉值來獲取其描述值如下:
??????? /// <summary>
??????? /// 根據枚舉值來獲取描述信息
??????? /// </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;
??????? }
但是這種方法是比較單一的,只能根據一個枚舉值來獲取一個描述信息。
以下便可以實現獲取所有的枚舉值和秒速信息
?/// <summary> ???????
/// 根據枚舉類型來獲取枚舉值和枚舉描述信息 ???????
/// </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;
}
這樣之后我們可以輕松的通過鍵值對來輕松的獲取我們先要的值或者描述信息。
?
------------------------哇!我這都三年5個月的博客齡了,不過一直沒有寫博客,希望通過我們分享,能給有需要的朋友們帶來幫助--------------
轉載于:https://www.cnblogs.com/hglSV/p/BigHGL.html
總結
以上是生活随笔為你收集整理的C#实现枚举的相关操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mac zsh切换bash bash切换
- 下一篇: c# char unsigned_dll