我有一個數據類Student,並且我有一個聚合類Student。 學生有兩個字符串類型的屬性:名稱和城市。用反射產生迭代器
我想要做的是可以選擇使用foreach機制來迭代哪些屬性。
我寫的代碼很有作用,它也很好看。 主要問題是性能:我使用yield關鍵字的行可能不是非常有效,但問題是多少?這是戲劇性的表現嗎?
有沒有更好的方法來實現這個功能? (補充說:我不想讓別人修改返回的Student對象,所以Linq提出的所有解決方案在這裏都不太好,爲了更清楚,我想:
屬性迭代+ foreach機制集成+學生類和學生的名單是隻讀 我怎樣才能做到這一點)
static void Main(string[] args)
{
Students students = new Students();
students.AddStudent(new Student { Age = 20, Name = "Stud1" , City="City1" });
students.AddStudent(new Student { Age = 46, Name = "Stud2" , City="City2"});
students.AddStudent(new Student { Age = 32, Name = "Stud3" , City="City3" });
students.AddStudent(new Student { Age = 34, Name = "Stud4" , City="city4" });
students.PropertyToIterate = eStudentProperty.City;
foreach (string studentCity in students)
{
Console.WriteLine(studentcity);
}
students.PropertyToIterate = eStudentProperty.Name;
foreach (string studentName in students)
{
Console.WriteLine(studentName);
}
}
public class Students :IEnumerable<object>
{
private List<Student> m_Students = new List<Student>();
private eStudentProperty m_PropertyToIterate = eStudentProperty.Name;
public eStudentProperty PropertyToIterate
{
get { return m_PropertyToIterate; }
set { m_PropertyToIterate = value; }
}
public void AddStudent(Student i_Student)
{
m_Students.Add(i_Student);
}
public IEnumerator<object> GetEnumerator()
{
for (int i = 0; i < m_Students.Count; ++i)
{
yield return (object)m_Students[i].GetType().GetProperty(PropertyToIterate.ToString()).GetValue(m_Students[i], null);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
public enum eStudentProperty
{
Name,
Age,
City
}
public class Student
{
public string Name { get; set; }
public string City { get; set; }
public int Age { get; set; }
}
你不能只拋出NotImplementedException! – leppie 2010-09-01 11:32:36
好看?!?! – flq 2010-09-01 12:45:19
這有幫助嗎? http://stackoverflow.com/questions/359495/how-to-make-ienumerablet-readonly – Odrade 2010-09-01 15:26:56