簡體   English   中英

從枚舉轉換為IEnumerable

[英]convert from enum to IEnumerable

你能幫我解決這個問題嗎?

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)時存在顯式轉換(您是否錯過了轉換?)

問題出在你的GetEnumValues方法中, Enum.GetValues返回的Array不是IEnumerable<T> 你需要施展它,即

Enum.GetValues(typeof(EnumType)).Cast<EnumType>();
    private IEnumerable<T> GetEnumValues()
    {
        Type enumType = EnumType;

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

我假設這行是拋出錯誤的那一行?:

return Enum.GetValues(enumType);

根據錯誤消息,您錯過了演員表。 你有沒有嘗試添加演員?:

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

Enum上的.GetValues()方法返回一個Array 雖然它可以枚舉(它實現IEnumerable ),但它不是通用的枚舉(它在編譯時實現IEnumerable<T> ,盡管文檔表明它將在運行時可用)。

為了將IEnumerable作為IEnumerable<T>返回,您需要將其強制轉換。 由於集合並不總是直接協變,因此提供了一個方便的.Cast<T>()方法來轉換集合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM