从枚举转换为IEnumerable

chu*_*nhu 12 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

} 
Run Code Online (Sandbox Code Playgroud)

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

Jam*_*mes 33

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

Enum.GetValues(typeof(EnumType)).Cast<EnumType>();
Run Code Online (Sandbox Code Playgroud)

  • @JakubKonecki是的,从.NET 2.0开始 - 请参阅[docs](http://msdn.microsoft.com/en-us/library/system.array.aspx). (2认同)
  • @RossPresser 是的,没错,不知何故我认为它完全错误,我现在肯定会使用该解决方案!所以最好的方法是:Enum.GetValues(typeof(EnumType)).Cast&lt;EnumType&gt;(),在答案中如何;) (2认同)