4

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

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

编译器抱怨:

无法将带有 [] 的索引应用于“T”类型的表达式

我明白那里有问题,但我不知道如何完成我想要的,最终是成功地制作

public class CustomClass<T> 

一种

public class CustomClass<T> : IEnumerable
4

2 回答 2

3

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

于 2012-12-19T15:34:27.873 回答
1

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

public class CustomClass<T> : IEnumerable where T : IList
于 2012-12-19T15:38:12.990 回答