9

如果我添加了一些额外的工具,我正在尝试使用自定义列表。我想将此列表应用于我创建的一长串自定义类。所有类都有一个 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>();
    }
}
4

1 回答 1

8

我认为您的自定义列表需要对泛型类型施加一些限制以允许这样做。我会将您的签名更新为类似

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; }
}

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

于 2013-05-10T05:24:30.943 回答