从枚举转换为IEnumerable

时间:2013-11-11 15:11:40

标签: c# enums

你能帮我解决这个代码的问题吗?

using System;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

namespace NTSoftHRM
{

    // ------------------------------------------------------------------------
    public class EnumValueList<T> : IEnumerable<T>
    {

        // ----------------------------------------------------------------------
        public EnumValueList()
        {
            IEnumerable<T> enumValues = GetEnumValues();
            foreach ( T enumValue in enumValues )
            {
                enumItems.Add( enumValue );
            }
        } // EnumValueList

        // ----------------------------------------------------------------------
        protected Type EnumType
        {
            get { return typeof( T ); }
        } // EnumType

        // ----------------------------------------------------------------------
        public IEnumerator<T> GetEnumerator()
        {
            return enumItems.GetEnumerator();
           // return ((IEnumerable<T>)enumItems).GetEnumerator();

        } // GetEnumerator

        // ----------------------------------------------------------------------
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        } // GetEnumerator

        // ----------------------------------------------------------------------
        // no Enum.GetValues() in Silverlight
        private IEnumerable<T> GetEnumValues()
        {
            List<T> enumValue = new List<T>();

            Type enumType = EnumType;

            return Enum.GetValues(enumType);

        } // GetEnumValues

        // ----------------------------------------------------------------------
        // members
        private readonly List<T> enumItems = new List<T>();

    } // class EnumValueList

} 

当bulid错误是: 无法将类型'System.Array'隐式转换为'System.Collections.Generic.IEnumerable'。返回Enum.GetValues(enumType)时存在显式转换(您是否错过了演员?)

3 个答案:

答案 0 :(得分:30)

问题在于您的GetEnumValues方法,Enum.GetValues会返回Array而不是IEnumerable<T>。你需要施放它,即

Enum.GetValues(typeof(EnumType)).Cast<EnumType>();

答案 1 :(得分:2)

    private IEnumerable<T> GetEnumValues()
    {
        Type enumType = EnumType;

        return Enum.GetValues(enumType).ToList<T>();
    } 

答案 2 :(得分:1)

我认为这一行是抛出错误的那一行?:

return Enum.GetValues(enumType);

根据错误消息,您错过了演员表。你有没有尝试添加演员?:

return Enum.GetValues(enumType).Cast<T>();

.GetValues()上的Enum方法返回an Array。虽然它可以枚举(它实现IEnumerable),但它不是通用的枚举(它在编译时它实现IEnumerable<T>,尽管{{ 3}}表示它将在运行时可用。)。

要将IEnumerable作为IEnumerable<T>返回,您需要投放它。由于集合并不总是直接协变,因此提供了一个方便的.Cast<T>()方法来转换集合。

相关问题