日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

OSS.Common获取枚举字典列表标准库支持

發布時間:2023/12/4 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 OSS.Common获取枚举字典列表标准库支持 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

上篇(.Net Standard擴展支持實例分享)介紹了OSS.Common的標準庫支持擴展,也列舉了可能遇到問題的解決方案。由于時間有限,同時.net standard暫時還沒有提供對DescriptionAttribute的支持,所以其中的轉化枚舉到字典列表的擴展當時按照第一種處理方式先行屏蔽,這次按照第三種方式完善一下。

  既然.net standard 下沒有提供對DescriptAttribute的支持,首先我先自定義一個Attribute來補充:

[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)]
public class OSDescriptAttribute : Attribute{
public OSDescriptAttribute(string description){
this.Description = description;}
public string Description { get; set; }}

  其次定義一個線程安全的字典,來全局緩存枚舉對應的枚舉字典列表,減少下次獲取的代碼執行:

private static ConcurrentDictionary<string, Dictionary<string, string>> enumDirs
=new ConcurrentDictionary<string, Dictionary<string, string>>();

  最后我們來實現獲取字典部分的具體操作:

public static Dictionary<string, string> ToEnumDirs(this Type enType,
bool isIntValue = true){#if NETFW if (!enType.IsEnum)#elseif (!enType.GetTypeInfo().IsEnum)#endifthrow new ArgumentException("獲取枚舉字典,參數必須是枚舉類型!"); string key = string.Concat(enType.FullName, isIntValue);Dictionary<string, string> dirs;enumDirs.TryGetValue(key, out dirs);
if (dirs != null)
return dirs.Copy();dirs = new Dictionary<string, string>();
var values = Enum.GetValues(enType);
foreach (var value in values){
var name = Enum.GetName(enType, value);
string resultValue = isIntValue ? ((int) value).ToString() : value.ToString()
;#if NETFW
var attr = enType.GetField(name)?.GetCustomAttribute<OSDescriptAttribute>();
#elsevar attr = enType.GetTypeInfo().GetDeclaredField(name)?.GetCustomAttribute<OSDescriptAttribute>();#endifdirs.Add(resultValue, attr == null ? name : attr.Description);}enumDirs.TryAdd(key, dirs);
return dirs.Copy();}

以后我們就可以在所有的業務的代碼中進行 ?typeof(枚舉類型).ToEnumDirs() ?的方法來獲取枚舉對應的字典列表,例如:

typeof (ResultTypes).ToEnumDirs();

如有其它疑問,歡迎關注公眾號(osscoder):

原文地址:http://www.cnblogs.com/sunhoy/p/6388528.html


.NET社區新聞,深度好文,微信中搜索dotNET跨平臺或掃描二維碼關注

總結

以上是生活随笔為你收集整理的OSS.Common获取枚举字典列表标准库支持的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。