public static T StringToEnum<T>(string name) { return (T)Enum.Parse(typeof(T), name); } public T NumToEnum<T>(int number) { return (T)Enum.ToObject(typeof(T), number); }
Example:
public enum DaysOfWeek { Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } public enum MonthsInYear { January, February, March, April, May, June, July, August, September, October, November, December } DaysOfWeek d = StringToEnum<DaysOfWeek>("Monday"); //d is now DaysOfWeek.Monday MonthsInYear m = StringToEnum<MonthsInYear>("January"); //m is now MonthsInYear.January
如果Enum中沒有相對的value, 就會throw exception:
DaysOfWeek d = StringToEnum<DaysOfWeek>("Katillsday"); //throws an ArgumentException //Requested value "Katillsday" was not found.
它提供了一個簡單的argument check, 這就行了:
if(Enum.IsDefined(typeof(DaysOfWeek), "Katillsday")) StringToEnum<DaysOfWeek>("Katillsday");
可是轉眼又看到有關performance及安全性的問題:The danger of over simplification
連MSDN上也說不要用Enum.IsDefine(), M$大哥啊, 忽悠我啊?!
既然問題對我影響好像不大......就當過關了
但還是看了相關的資料, 說不定日後再要面對這個問題(希望不要)
C# Enum.Parse() Bug
More C# 'enum' Wackiness
Common Type System—Type Safety Limitations 這個讚
沒有留言:
發佈留言