我想自定义列表。我主要是想通了,但我遇到了一个问题。这里是我一起工作的代码:如何自定义列表<T>?
public class MyT
{
public int ID { get; set; }
public MyT Set(string Line)
{
int x = 0;
this.ID = Convert.ToInt32(Line);
return this;
}
}
public class MyList<T> : List<T> where T : MyT, new()
{
internal T Add(T n)
{
Read();
Add(n);
return n;
}
internal MyList<T> Read()
{
Clear();
StreamReader sr = new StreamReader(@"../../Files/" + GetType().Name + ".txt");
while (!sr.EndOfStream)
Add(new T().Set(sr.ReadLine())); //<----Here is my error!
sr.Close();
return this;
}
}
public class Customer : MyT
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Item : MyT
{
public int ID { get; set; }
public string Category { get; set; }
public string Name { get; set; }
public double Price { get; set; }
}
public class MyClass
{
MyList<Customer> Customers = new MyList<Customer>();
MyList<Item> Items = new MyList<Item>();
}
在代码中,你可以看到,我想创建一个自定义列表。 在这里,您还可以看到我拥有的许多课程中的两个。所有的课程都有一个ID。 所有类都与自定义列表匹配。 这个问题似乎在MyList<T>.Read()
- Add(new T().Set(sr.ReadLine()));
最后,我得到MyT不能转换为T.我需要知道如何解决它。
扩展方法很可能是除非子类对您真的很重要,否则会更好。 – 2013-05-10 09:51:01
'T:MyT'如果T只能是MyT,为什么要使用泛型? – I4V 2013-05-10 09:52:57
I4V:它使用编译为MyT的通用版本,而不是仅使用内部对象的非泛型,这可能由于投射而变慢;并且可以有MyT的子类... – 2013-05-10 10:00:50