In fact, you could do what Paw offers , even with a general limitation, if you can move this method to your class:
public abstract class Helper<T> { public static string DoSomething<TEnum>(TEnum value) where TEnum: struct, T { if (!Enum.IsDefined(typeof(TEnum), value)) { value = default(TEnum); }
Then you would do, for example:
MyEnum x = MyEnum.SomeValue; MyEnum y = (MyEnum)100; // Let say this is undefined. EnumHelper.DoSomething(x); // generic type of MyEnum can be inferred EnumHelper.DoSomething(y); // same here
As Conrad Rudolph notes in a comment, default(TEnum) in the code above will be evaluated to 0, regardless of whether or not a value is defined for 0 for this type of TEnum . If this is not what you want, Will respond , this is by far the easiest way to get the first specific value ( (TEnum)Enum.GetValues(typeof(TEnum)).GetValue(0) ).
On the other hand, if you want to do this with extreme and cache the result so that you do not always need to insert it, you can do this:
public abstract class Helper<T> { static Dictionary<Type, T> s_defaults = new Dictionary<Type, T>(); public static string DoSomething<TEnum>(TEnum value) where TEnum: struct, T { if (!Enum.IsDefined(typeof(TEnum), value)) { value = GetDefault<TEnum>(); }
Dan tao
source share