4

I have a generic class which uses a type parameter

public class CustomClass<T> 

and I am using it with an ObservableCollection<someClass> Type. All I want is to make this class implement the IEnumerable interface, so I did the following:

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

The compiler complains:

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

I understand that there is something wrong there, but I don't know how to accomplish what I want, which finally is to successfully make

public class CustomClass<T> 

a

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 に答える