我有一个使用类型参数
的泛型类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>
a
public class CustomClass<T> : IEnumerable
答案 0 :(得分:3)
尝试实施IEnumerable<T>
而不是IEnumerable
答案 1 :(得分:1)
您必须指定T可以编入索引:
public class CustomClass<T> : IEnumerable where T : IList