日期:2014-05-16  浏览次数:20922 次

为enum写了一个扩展方法,用模板,编译失败了。错在哪里?
我有一个简单的枚举类型,我想在用的地方能从字符串直接转:

    enum E
    {
        yes,
        no
    }
    class Program
    {
        static void Main(string[] args)
        {
            E e1 = "yes".EnumParse<E>();
            E e2 = "no".EnumParse<E>();
        }
    }

为此,我想为E这个enum类型创建一个扩展方法,想用模板来写,如下:

    public static TEnum EnumParse<TEnum>(this string value) where TEnum : struct
    {
        TEnum result;
        if (!Enum.TryParse<TEnum>(value, true, out result)) throw new ArgumentException();
        return result;
    }

一编译一堆错。我对模板的语法不熟悉,我的代码应该写成什么样才是正确的呢?
------解决方案--------------------

//放在静态类里面
public static class EnumExt
{
    public static TEnum EnumParse<TEnum>(this string value) where TEnum : struct
    {
        TEnum result;
        if (!Enum.TryParse<TEnum>(value, true, out result)) throw new ArgumentException();
        return result;
    }
}