在派生自 List<T> 的 class 上调用基本方法

Calling base methods on class derived from List<T>

我有一个 class 来自列表:

public class B : List<A>
{
}

如何在 B 上调用 List 方法?例如

var test = new B();
test = test.OrderBy(s=>s.SomeProperty);

非常感谢!

如果您询问如何将 test.OrderBy(...) 分配给 test,那么您需要这样做:

IEnumerable<A> test = new B();
test = test.OrderBy(s => s.SomeProperty);

但这样做会阻止您向 test 添加任何内容。

你需要这样做:

B b = new B();
/* add items to `b` here */
IEnumerable<A> test = b;
test = test.OrderBy(s => s.SomeProperty);

根据 ,你想将 IEnumerable<T>.OrderBy() 的结果赋给一个 B 变量。

你不能那样做,因为没有从 IEnumerable<T>(或者更确切地说 IOrderedEnumerable<T>B.

的隐式转换

正如你做不到的那样:

List<string> stringList = new List<string> { "foo", "bar" };
stringList = stringList.OrderBy(s => s);

你不能用你自己的类型来做到这一点。对于上面的代码,修复很简单:

stringList = stringList.OrderBy(s => s).ToList();

例如,您可以实现构造函数、扩展方法或隐式或显式转换来解决此问题:

public class B : List<A>
{
    public B(IEnumerable<A> items)
    {
        base.AddRange(items);
    }
}

然后分配一个新实例:

test = new B(test.OrderBy(s=>s.SomeProperty));

无论如何你不应该想从 List<T> 继承,阅读 Why not inherit from List<T>?