Attempts to parse flag enumeration per string

I have a โ€œlicenseโ€ class, which is a set of bundles of flags like this:

Public class License { UsageType Usage { get; set; } PlatformType Platform { get; set; } public enum UsageType { read = 1, write = 2, wipe = 4, all = 7 } public enum PlatformType { windows = 1, linux = 2, ios = 4, all = 7 } etc... } 

The fact is that different flags of the same category can be OR'd together to form a profile of what the user can do with the specified license. Now I'm trying to show the Usage and Platform values โ€‹โ€‹in a human-friendly way, for example, if Usage == UsageType.read | UsageType.write, then it should be parsed as "read, write."

I did this successfully with one type of enumeration, checking the value for each flag and adding enumitem.ToString () for each flag that it has for the string. Since I have many of these enumerations and meanings, I would like to suggest a more general approach.

I came up with this (below), but since I am not very familiar with the template functions in C #, so I do not know why this does not work, but at least it should illustrate what I mean:

 private string parseEnum<T>(T value) { string ret = ""; foreach (var ei in (T[])Enum.GetValues(typeof(T))) { if (value.HasFlag(ei)) ret += ei.ToString() + ", "; } ret = ret.substring(0, ret.Length-1); return ret; } 

This suggests that T does not contain a definition for "HasFlag", but how could it be now if he does not know what T is?

+7
generics enums c # parsing
source share
1 answer

You should use FlagsAttribute , which makes the built-in ToString and Enum.Parse work the way you want. Also note that the convention is that flag rename names must be multiple), i.e. UsageTypes instead of UsageType .

 [Flags] public enum UsageTypes { Read = 1, Write = 2, Wipe = 4, All = 7 } [Flags] public enum PlatformTypes { Windows = 1, Linux = 2, iOs = 4, All = 7 } var e1 = License.UsageTypes.Read | License.UsageTypes.Write; var s = e1.ToString(); Debug.Assert(s == "Read, Write"); var e2 = (License.UsageTypes)Enum.Parse(typeof(License.UsageTypes), s); Debug.Assert(e1 == e2); 
+25
source share

All Articles