在C#中创建和使用自定义List

我正在尝试使用自定义列表,我已经添加了一些额外的工具。 我想将此列表应用于我创建的一长串自定义类。 所有类都有一个ID号,List中的一些工具使用ID。

这是我尝试使用的代码的一部分。 我希望这能帮助你理解我的问题。

namespace Simple_Point_of _Sales_System { public class MyList : List { internal int SetID() { return this.Max(n => n.ID) + 1; } internal T Find(int ID) { return this.Find(n => n.ID == ID); } internal T Add(T n) { Read(); Add(n); Write(); return n; } internal void Remove(int ID) { Read(); if (this.Exists(t => t.ID == ID)) RemoveAll(t => t.ID == ID); else MessageBox.Show(GetType().Name + " " + ID + " does not exist.", "Missing Item", MessageBoxButtons.OK, MessageBoxIcon.Error); Write(); } internal void Edit(int ID, T n) { Read(); if (this.Exists(t => t.ID == ID)) this[FindIndex(t => t.ID == ID)] = n; else MessageBox.Show(GetType().Name + " " + ID + " does not exist.", "Missing Item", MessageBoxButtons.OK, MessageBoxIcon.Error); Write(); } internal MyList Read() { Clear(); StreamReader sr = new StreamReader(@"../../Files/" + GetType().Name + ".txt"); while (!sr.EndOfStream) Add(new T().Set(sr.ReadLine())); sr.Close(); return this; } internal void Write() { StreamWriter sw = new StreamWriter(@"../../Files/" + GetType().Name + ".txt"); foreach (T n in this) sw.WriteLine(n.ToString()); sw.Close(); } } public class Customer { public int ID; public string FirstName; public string LastName; } public class Item { public int ID { get; set; } public string Category { get; set; } public string Name { get; set; } public double Price { get; set; } } public class MyClass { MyList Customers = new MyList(); MyList Items = new MyList(); } } 

我认为你的自定义列表需要对generics类型设置一些限制以允许它。 我会将你的签名更新为类似的东西

 public class MyList : List where T : IIdentity { .... } 

在这里,我使用IIdentity作为定义ID的接口,但它也可以是一个类。

要更新你的代码我会做这样的事情:

 public interface IIdentity { int ID { get; } } public class Customer : IIdentity { public int ID { get; set;} public string FirstName; public string LastName; } public class Item : IIdentity { public int ID { get; set; } public string Category { get; set; } public string Name { get; set; } public double Price { get; set; } } 

我将Customer的ID更改为属性而不是实例变量。