[英]Creating and using a custom List<T> in C#
我正在尝试使用自定义列表,我已经添加了一些额外的工具。 我想将此列表应用于我创建的一长串自定义类。 所有类都有一个ID号,List中的一些工具使用ID。
这是我尝试使用的代码的一部分。 我希望这能帮助你理解我的问题。
namespace Simple_Point_of _Sales_System
{
public class MyList<T> : List<T>
{
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<T> 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<Customer> Customers = new MyList<Customer>();
MyList<Item> Items = new MyList<Item>();
}
}
我认为你的自定义列表需要对泛型类型设置一些限制以允许它。 我会将你的签名更新为类似的东西
public class MyList<T> : List<T> 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更改为属性而不是实例变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.