gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:39:28 24 4
gpt4 key购买 nike

如果我添加了一些额外的工具,我正在尝试使用自定义列表。我想将此列表应用于我创建的一长串自定义类。所有类都有一个 ID 号,列表中的一些工具使用该 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的接口(interface),但它也可以是一个类。

要更新您的代码,我会这样做:

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 更改为属性而不是实例变量。

关于c# - 在 C# 中创建和使用自定义 List<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16475423/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com