c# – 制作一个通用类IEnumerable

我有一个使用类型参数的泛型类

public class CustomClass<T> 

我正在使用它与ObservableCollection< someClass>类型.我想要的是让这个类实现IEnumerable接口,所以我做了以下事情:

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

编译器抱怨:

Cannot apply indexing with [] to an expression of type ‘T’

我知道那里有一些问题,但我不知道如何实现我想要的,最终是成功的

public class CustomClass<T> 

一个

public class CustomClass<T> : IEnumerable

解决方法:

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

相关文章

如何在Silverlight4(XAML)中绑定IsEnabled属性?我试过简单的...
我正在编写我的第一个vb.net应用程序(但我也会在这里标记c#,...
ProcessFile()是在UIThread上运行还是在单独的线程上运行.如...
我从同行那里听说,对sharepoint的了解对职业生涯有益.我们不...
我正在尝试保存一个类我的类对象的集合.我收到一个错误说明:...
我需要根据Silverlight中的某些配置值设置给定控件的Style.我...