CSharp Enumerate through nullable Enums

时间:2015-06-26 10:16:54

标签: c# enums

One piece of code is worth a thousand words...

public enum enTest { a, b, c }

public void PrintEnum<T>()
{
    foreach (var E in Enum.GetValues(typeof(T)))
    Debug.WriteLine(E.ToString());
}

PrintEnum<enTest>();
PrintEnum<enTest?>();    // This will cause failure in Enum.GetValues()

The above is simplified from a larger problem to illustrate the failure.

Does anyone know how can I iterate through (or get all the values inside) when someone passing me a Nullable Enum?

Thanks in advance.

1 个答案:

答案 0 :(得分:2)

How about this?

public static void PrintEnum<T>()
        {
            Type t = typeof (T);
            if (t.IsGenericType)
            {
                //Assume it's a nullable enum
                t = typeof (T).GenericTypeArguments[0];
            }

            foreach (var E in Enum.GetValues(t))
                Console.WriteLine(E.ToString());
        }