2

我有一个返回所有枚举值的方法(但这并不重要)。重要的是它需要T并返回IEnumerable<T>

    private static IEnumerable<T> GetAllEnumValues<T>(T ob)
    {
        return System.Enum.GetValues(ob.GetType()).Cast<T>();
    }

或者

    private static IEnumerable<T>  GetAllEnumValues<T>(T ob) 
    {
        foreach (var info in ob.GetType().GetFields(BindingFlags.Public | BindingFlags.Static))
        {
            yield return (T) info.GetRawConstantValue();
        }
    }

要使用此方法,您需要使用类的实例调用它 - 在这种情况下,使用我们想要探索的枚举中的任何值:

    GetAllEnumValues( Questions.Good );

我想更改方法的签名以接受System.Type并能够像这样调用它:

    GetAllEnumValues( typeof(Questions ));

我不知道签名会是什么样子:

    private static IEnumerable<?>  GetAllEnumValues<?>(System.Type type) 

以及如何应用铸造或Convert.ChangeType实现这一目标。

我不想打电话GetAllEnumValues<Questions>( typeof(Questions ));

这甚至可能吗?

4

1 回答 1

5

为什么不创建一个开放的泛型类型,您可以使用枚举指定它,如下所示:

private static IEnumerable<T> GetAllEnumValues<T>() 
{
    if(typeof(T).IsEnum)
        return Enum.GetValues(typeof(T)).Cast<T>();
    else
        return Enumerable.Empty<T>(); //or throw an exception
}

然后有枚举

enum Questions { Good, Bad }

这段代码

foreach (var question in GetAllEnumValues<Questions>())
{
    Console.WriteLine (question);
}

将打印:

Good
Bad
于 2013-08-06T01:37:03.810 回答