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