public static T Convert2Enum<T>(object obj, T defaultValue) where T : struct, IComparable, IFormattable, IConvertible
{
///【*** 2012-2-18-233447】这里实在是没有办法在声明泛型T的时候约束他一定要继承自System.Enum,至少在.NET 4.0里面都还是不行的,不只是CRC遇到这个问题,
///网上很多帖子也是关于这个的,但是只能在运行时抛出异常,而不能在编译时控制编译。
///http://stackoverflow.com/questions/79126/create-generic-method-constraining-t-to-an-enum
///http://code.google.com/p/unconstrained-melody/downloads/list
if (obj == null)
return defaultValue;
if (typeof(T).IsEnum)
{
T t = defaultValue;
string val = obj.ToString();
return Enum.TryParse(val, true, out t) && Enum.IsDefined(typeof(T), t)
? (T)Enum.Parse(typeof(T), val)
: defaultValue;
}
throw new Exception("【*** 2014-1-26-115324】运行时异常,输入泛型类型<T>类型应该是一个枚举类型。");
}