【发布时间】:2012-12-15 18:27:15
【问题描述】:
我有一个使用类型参数的泛型类
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
【问题讨论】:
-
这听起来/看起来是一个索引器问题。除非您对声明索引器的接口使用通用约束,否则确实 - 对于任意 T.
标签: c# silverlight windows-phone-7 generics ienumerable