【问题标题】:How do I customize List<T>? [duplicate]如何自定义 List<T>? [复制]
【发布时间】:2013-05-10 09:47:12
【问题描述】:

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

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

【问题讨论】:

  • where T : MyT 如果T只能是MyT,那你为什么要用泛型?
  • I4V:它使用编译为 MyT 的泛型版本,而不是仅使用内部对象的非泛型版本,由于强制转换可能会更慢;并且可以有 MyT 的子类...
  • 像这样扩展List&lt;&gt; 感觉非常错误。最好有一个完全不同的类来从文件创建列表。
  • 您要向 List 类添加什么功能?以我的经验,扩展 List 类很少是要走的路。相反,如果类型 A 需要维护类型 B 的集合,则使用常规 List 并在类型 A 中添加一些方法,以对 List 执行特定操作。
  • @Makai:我会考虑在我自己的类中封装一个 List 而不是从它继承;

标签: c# list customization


【解决方案1】:

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())));

【讨论】:

  • 我试过你推荐的。您给出的第一个用法仍然给出与以前完全相同的错误。第二个给出了一个新的错误。 错误 6:无法从用法中推断方法“MyT.Set(string)”的类型参数。尝试明确指定类型参数。”我不知道这是什么意思。
  • @Makai:对不起,该方法当然应该有返回类型T,而不是MyT。当您从第二个代码中得到该错误时,这意味着您修改了第一个示例中的方法,并尝试像第二个示例中一样使用它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-13
  • 2012-04-20
  • 2016-09-28
  • 2021-09-12
  • 2011-06-25
  • 2019-10-03
相关资源
最近更新 更多