我正在尝试实现自己的列表类。只是为了培训,以更好地了解事物的工作原理。
我有类似的东西:
public class TestClass {
public int[] List;
// Add(), ...
}
我希望能够像这样检索数组(这是
TestClass
的属性):var testClass = new TestClass();
int[] list = testClass; // without the ".List" list would point to the array
而不是这样:
var testClass = new TestClass();
int[] list = testClass.List;
可以使用与c#内置通用列表类相同的方式。
我怎样才能做到这一点(如果可能的话)?
更新
我将“列表”更改为
int[]
,希望对您有所帮助。我知道我可以做类似的事情:
int[] list = new int[10];
但是我需要
TestClass
,因为我需要有关数组的其他一些(扩展)属性以及更多的自定义方法。更新2
也许这将使事情变得更加清晰。
我试图找出在这种情况下通用
List<T>
类的工作方式:var list = new List<T>();
foreach(var oneElement in list)
就我而言,我必须这样做:
var list = new TestClass();
foreach(var oneElement in list.List)
我希望能够以与
.NET
或C#
List<T>
类检索其“基础数组”相同的方式检索数组。 最佳答案
如果允许var list
具有类型IEnumerable<T>
,ICollection<T>
或IList<T>
之一,则只需实现接口IEnumerable<T>
,ICollection<T>
或IList<T>
之一:
public class TestClass : IList<SomeTypeOrGenericT>
{
public SomeTypeOrGenericT[] List;
// ...
// members of IList<SomeTypeOrGenericT>
}