OSS. Common supports standard library for retrieving enumerated Dictionary lists, and oss. common Enumeration
In the previous article (. Net Standard extension supports instance sharing), we introduced the Standard library support extension for OSS. Common, as well as the solutions that may encounter problems. Due to limited time, at the same time. net standard does not yet provide support for DescriptionAttribute. Therefore, the extended conversion enumeration to dictionary list is blocked in the first way. This time, the third method is used to improve it.
Since the. net standard does not provide support for DescriptAttribute, I first define an Attribute to add:
[AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)] public class OSDescriptAttribute : Attribute { public OSDescriptAttribute(string description) { this.Description = description; } public string Description { get; set; } }
Next, define a thread-safe dictionary to globally cache the list of enumeration dictionaries corresponding to enumeration, reducing the code execution obtained next time:
private static ConcurrentDictionary<string, Dictionary<string, string>> enumDirs =new ConcurrentDictionary<string, Dictionary<string, string>>();
Finally, we can perform the following operations to obtain the dictionary:
Public static Dictionary <string, string> ToEnumDirs (this Type enType, bool isIntValue = true) {# if NETFW if (! EnType. IsEnum) # else if (! EnType. GetTypeInfo (). IsEnum) # endif throw new ArgumentException ("retrieve enumeration dictionary. The parameter must be of the enumeration type! "); 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> (); # else var attr = enType. GetTypeInfo (). GetDeclaredField (name )?. GetCustomAttribute <OSDescriptAttribute> (); # endif dirs. Add (resultValue, attr = null? Name: attr. Description);} enumDirs. TryAdd (key, dirs); return dirs. Copy ();}
In the future, we can use the typeof (Enumeration type). ToEnumDirs () method in all business code to obtain the dictionary list corresponding to the enumeration, for example:
typeof (ResultTypes).ToEnumDirs();
For the code, see github.
If you are interested in the OSS open-source series, you can refer to the osscoder ):