转载 

C#通用Convert2Enum

分类:    877人阅读    IT小君  2015-11-18 09:51
        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>类型应该是一个枚举类型。");
        }
支付宝打赏 微信打赏

如果文章对你有帮助,欢迎点击上方按钮打赏作者

 工具推荐 更多»