7

我敢肯定这是相当微不足道的,但我无法做到正确。

public static string DoSomething(this Enum value)
 {
     if (!Enum.IsDefined(value.GetType(), value))
     {
         // not a valid value, assume default value
         value = default(value.GetType()); 
     }

     // ... do some other stuff
 }

该行value = default(value.GetType());无法编译,但希望您能看到我正在尝试的内容。我需要将 Enum 参数设置为它自己类型的默认值。

4

5 回答 5

5

我不太确定您要在这里做什么,但是可以编译的“默认”行的一个版本是这样的:

 value = (Enum)Enum.GetValues(value.GetType()).GetValue(0);

或者,甚至更清洁(来自 Paw,在评论中,谢谢):

 value = (Enum) Enum.ToObject(value.GetType(), 0);

只有当您知道枚举的第一个元素的值为零时,第二个版本才能正常工作。

于 2010-11-04T12:31:56.647 回答
2

如果您可以将此方法移至其自己的类,则即使使用通用约束,您实际上也可以执行Paw 的建议:

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);
        }

        // ... do some other stuff

        // just to get code to compile
        return value.ToString();
    }
}

public class EnumHelper : Helper<Enum> { }

然后你会这样做,例如:

MyEnum x = MyEnum.SomeValue;
MyEnum y = (MyEnum)100; // Let's say this is undefined.

EnumHelper.DoSomething(x); // generic type of MyEnum can be inferred
EnumHelper.DoSomething(y); // same here

正如 Konrad Rudolph 在评论中指出的那样,default(TEnum)上面的代码将评估为 0,无论是否为给定TEnum类型定义了 0 值。如果这不是您想要的,Will 的回答无疑提供了获取第一个定义值 ( (TEnum)Enum.GetValues(typeof(TEnum)).GetValue(0)) 的最简单方法。

另一方面,如果你想把它发挥到极致,并缓存结果,这样你就不必总是把它装箱,你可以这样做:

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>();
        }

        // ... do some other stuff

        // just to get code to compile
        return value.ToString();
    }

    public static TEnum GetDefault<TEnum>() where TEnum : struct, T
    {
        T definedDefault;
        if (!s_defaults.TryGetValue(typeof(TEnum), out definedDefault))
        {
            // This is the only time you'll have to box the defined default.
            definedDefault = (T)Enum.GetValues(typeof(TEnum)).GetValue(0);
            s_defaults[typeof(TEnum)] = definedDefault;
        }

        // Every subsequent call to GetDefault on the same TEnum type
        // will unbox the same object.
        return (TEnum)definedDefault;
    }
}
于 2010-11-04T12:45:26.560 回答
1

Activator.CreateInstance(typeof(ConsoleColor))似乎工作

于 2010-11-04T12:05:22.863 回答
-1

Enum默认情况下,将其first value作为default value

于 2010-11-04T12:16:11.873 回答
-1

您是否考虑过使其成为通用方法?

public static string DoSomething<T>(Enum value)
{
    if (!Enum.IsDefined(typeof(T), value))
    {
        value = (T)Enum.ToObject(typeof(T), 0);
    }
    // ... do some other stuff
}

方法的调用者应该知道类型。

于 2010-11-04T12:28:36.383 回答