【发布时间】:2015-05-13 03:17:36
【问题描述】:
我想在我的班级中添加不同的索引器实现:
SpecificCollection
public class SpecificCollection<T> : ISpecificCollection <T>
{
public int this[int index]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public object this[int index]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public string this[int index]
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
public event void OnAddElement;
public event void OnRemoveElement;
public void AddNewElement(T element)
{
throw new NotImplementedException();
}
public void DeleteElement(int index)
{
throw new NotImplementedException();
}
public int Count
{
get
{
throw new NotImplementedException();
}
set
{
throw new NotImplementedException();
}
}
}
StudentSpecificCollection
public class StudentSpecificCollection : SpecificCollection<Student>
{
private string[] arrName;
private int[] arrAge;
private object[] arrStudent ;
public int ISpecificCollectionIndexers<Student>.this[int index]
{
get
{
return arrAge[index];
}
set
{
arrAge[index] = value;
}
}
object ISpecificCollectionIndexers<Student>.this[int index]
{
get
{
return arrStudent[index];
}
set
{
arrStudent[index] = value;
}
}
string ISpecificCollectionIndexers<Student>.this[int index]
{
get
{
return arrName[index];
}
set
{
arrName[index] = value;
}
}
public event void OnAddElement;
public event void OnRemoveElement;
public void AddNewElement(Student element)
{
object objStudent = arrStudent.Where(x => x != null).LastOrDefault();
int index = (objStudent == null) ? 0 : Array.IndexOf(arrStudent, objStudent);
arrName[index] = element.Name ;
arrAge[index] = element.Age;
arrStudent[index] = element;
}
public void DeleteElement(int index)
{
if (index > Count - 1) return;
arrName[index] = null;
arrAge[index] = -1;
arrStudent[index] = null;
}
public int Count
{
get
{
return arrName.Where(x=>x !=null).Count();
}
set
{
}
}
public StudentSpecificCollection()
{
arrName = new string[100];
arrAge = new int[100];
arrStudent = new object[100];
}
}
所以我需要知道:
- 如何使用不同的索引器实现?
- 在此类中实施不同类型索引的最佳做法是什么?
- 在哪些情况下自定义索引比使用不同的 C# 集合更好?
【问题讨论】:
-
您不能创建仅在返回类型上有所不同的方法的重载。
-
@Spo1ler 谢谢,我不是在问错误的原因很清楚,但我需要一个建议来实现不同类型的索引器
-
您只能让一个索引器返回您所在班级的对象,名称和年龄等属性可以通过该对象访问。
-
@LamloumiAfif 你可以实现接口
-
您的代码没有意义。为什么不将
Student对象本身存储在一个集合中?
标签: c# .net oop collections interface