I have two questions, one deriving from the other.
- I'm trying to parse an Enum that has the
FlagsAttribute
attribute to another enum which also has the same attribute. My attempt is in the code below. If someone has found an efficient way of doing this please let me know. As my current method involves iterating for all set flags and parsing one by one and then logically OR'ing them together. - In attempting to solve this I got this error:
The type 'Program.Test' cannot be used as type parameter 'T' in the generic type or method 'Program.Parse<T>(string, bool)'. There is no boxing conversion from 'Program.Test' to 'System.FlagsAttribute'.
What I'm really looking for here is an explanation as to why. Obviously both enums have theFlags
attribute which is shorthand forFlagsAttribute
so shouldn't there already exist a conversion?
Also link for the lazy : DotNetFiddle
Code:
public static void Main()
{
var q = Parse<TestType>((Test.ACT | Test.SAT_2016).ToString());
Console.WriteLine(string.Format("Type: {0}\t Value: {1}", q.GetType(), q));
// */
}
public static T Parse<T>(string value, bool ignoreCase = false)
where T : FlagsAttribute , IComparable, IFormattable, IConvertible
{
if (value.ToString().Contains(",")){
var parts = value.ToString().Split(',');
var results = new List<T> ();
var final = default(T);
foreach (var part in parts){
try {
final |= (T)Enum.Parse(typeof(T), part, ignoreCase) ;
}catch (Exception e){
Console.WriteLine("Got exception");
/* Supressed */
}
}
return final;
}else{
return (T) Enum.Parse(typeof(T), value.ToString(), ignoreCase);
}
}
[Flags]
public enum Test{
ACT = 32,
SAT_2016 = 65536,
};
[Flags]
public enum TestType {
ACT = 4,
SAT_2016 = 39,
};