首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >生成泛型类IEnumerable

生成泛型类IEnumerable
EN

Stack Overflow用户
提问于 2012-12-15 18:27:15
回答 2查看 3.4K关注 0票数 4

我有一个泛型类,它使用类型参数。

代码语言:javascript
复制
public class CustomClass<T> 

我用的是ObservableCollection<someClass>类型。我只想让这个类实现IEnumerable接口,所以我做了以下工作:

代码语言:javascript
复制
public class CustomClass<T> : IEnumerable

#region Variable Declarations
 ...
#endregion

#region Constructor and CustomClass<T> properties and methods
 ...
#endregion

#region Here I add the code for IEnumerable to work

private T theObservableCollection
    {
        get
        {
            if (typeof(T) == typeof(ObservableCollection<someClass>))
                return theObservableCollection;
            else
                return default(T);
        }
    }

    //Create a public GetEnumerator method, the basic ingredient of an IEnumerable interface.
    public IEnumerator GetEnumerator()
    {
        IEnumerator r = (IEnumerator)new SettingEnumerator(this);
        return r;
    }

    //Create a nested-class
    class SettingEnumerator
    {
        int index;
        CustomClass<T> sp;

        public SettingEnumerator(CustomClass<T> str_obj)
        {
            index = -1;
            sp = str_obj;
        }

        public object Current
        {
            get
            {
                return sp.theObservableCollection[index];
            }
        }

        public bool MoveNext()
        {
            if (index < sp.theObservableCollection.Length - 1)
            {
                index++;
                return true;
            }
            return false;
        }

        public void Reset()
        {
            index = -1;
        }
    }  


#endregion

编译器抱怨:

不能将[]索引应用于'T‘类型的表达式

我知道那里出了点问题,但我不知道如何实现我想要的,这最终是成功的

代码语言:javascript
复制
public class CustomClass<T> 

一个

代码语言:javascript
复制
public class CustomClass<T> : IEnumerable
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-12-19 15:34:27

尝试实现IEnumerable<T>而不是IEnumerable

票数 3
EN

Stack Overflow用户

发布于 2012-12-19 15:38:12

您必须指定T可以被索引:

代码语言:javascript
复制
public class CustomClass<T> : IEnumerable where T : IList
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13894928

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档