【问题标题】:Taking a System.Type in and return an IEnumerable of this type获取 System.Type 并返回此类型的 IEnumerable
【发布时间】:2013-08-06 01:31:30
【问题描述】:

我有一个返回所有枚举值的方法(但这并不重要)。重要的是它接受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&lt;Questions&gt;( typeof(Questions ));

这可能吗?

【问题讨论】:

    标签: c# generics casting ienumerable


    【解决方案1】:

    为什么不创建一个开放的泛型类型,你可以用枚举来指定它,像这样:

    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
    

    【讨论】:

    • 呵呵,你一直在改进你的答案,但从一开始就是正确的。很明显,当我现在看到它时,我只是过度设计了我的代码:)
    • @Tymek 我只是想提供一些细节,例如异常处理。如您所知,魔鬼在细节中;)
    猜你喜欢
    • 1970-01-01
    • 2010-09-15
    • 2010-09-27
    • 1970-01-01
    • 2011-02-22
    • 1970-01-01
    • 1970-01-01
    • 2014-11-04
    • 2018-11-27
    相关资源
    最近更新 更多