【发布时间】:2013-05-10 09:47:12
【问题描述】:
我正在尝试自定义列表。我基本上已经弄清楚了,但遇到了一个问题。这是我正在使用的代码:
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。我需要知道如何修复它。
【问题讨论】:
-
where T : MyT如果T只能是MyT,那你为什么要用泛型? -
I4V:它使用编译为 MyT 的泛型版本,而不是仅使用内部对象的非泛型版本,由于强制转换可能会更慢;并且可以有 MyT 的子类...
-
像这样扩展
List<>感觉非常错误。最好有一个完全不同的类来从文件创建列表。 -
您要向 List 类添加什么功能?以我的经验,扩展 List 类很少是要走的路。相反,如果类型 A 需要维护类型 B 的集合,则使用常规 List 并在类型 A 中添加一些方法,以对 List 执行特定操作。
-
@Makai:我会考虑在我自己的类中封装一个 List 而不是从它继承;
标签: c# list customization