简体   繁体   English

接受System.Type并返回此类型的IEnumerable

[英]Taking a System.Type in and return an IEnumerable of this type

I have a method which returns all enum values (but this is not material). 我有一个返回所有枚举值的方法(但这不是实质性的)。 The important bit is that it takes T and returns IEnumerable<T> . 重要的一点是它需要T并返回IEnumerable<T>

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

or 要么

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

To use this method you need to call it with an instance of the class - in this case with any value from the enum we want to explore: 要使用此方法,您需要使用该类的实例来调用它-在这种情况下,需要使用我们想要研究的枚举中的任何值:

    GetAllEnumValues( Questions.Good );

I would like to change the signature of the method to take a System.Type in and to be able to call it like this: 我想更改方法的签名以采用System.Type并能够这样调用它:

    GetAllEnumValues( typeof(Questions ));

I don't know how the signature would look like: 我不知道签名会是什么样子:

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

and how to apply casting or Convert.ChangeType to achieve this. 以及如何应用强制转换或Convert.ChangeType来实现此目的。

I don't want to have to call GetAllEnumValues<Questions>( typeof(Questions )); 我不想调用GetAllEnumValues<Questions>( typeof(Questions ));

Is this even possible? 这有可能吗?

Why not to create a open generic type, which you can specify with an enum, like this: 为什么不创建一个开放的泛型类型,您可以使用枚举指定它,如下所示:

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
}

then having enum 然后有枚举

enum Questions { Good, Bad }

this code 此代码

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

will print: 将打印:

Good
Bad

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM