我有一个泛型类,它使用类型参数。
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发布于 2012-12-19 15:34:27
尝试实现IEnumerable<T>而不是IEnumerable
发布于 2012-12-19 15:38:12
您必须指定T可以被索引:
public class CustomClass<T> : IEnumerable where T : IListhttps://stackoverflow.com/questions/13894928
复制相似问题