如何自定义List<

本文关键字:List 自定义 | 更新日期: 2023-09-27 18:13:11

我正在尝试自定义列表。我已经弄清楚了,但我遇到了一个问题。下面是我正在使用的代码:

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。所有类都与自定义List匹配。问题似乎在MyList<T>.Read() - Add(new T().Set(sr.ReadLine()));最后,我知道MyT不能转换为t,我需要知道如何修复它

如何自定义List<

Set方法返回MyT类型,而不是特定类型。使其泛型,以便它可以返回特定的类型:

public T Set<T>(string Line) where T : MyT {
    int x = 0;
    this.ID = Convert.ToInt32(Line);
    return (T)this;
}

用法:

Add(new T().Set<T>(sr.ReadLine()));

或者将引用强制转换回特定类型:

Add((T)(new T().Set(sr.ReadLine())));