简体   繁体   English

C#,通用列表和继承

[英]C#, Generic Lists and Inheritance

I have a class called Foo that defines a list of objects of type A: 我有一个名为Foo的类,它定义了类型A的对象列表:

class Foo {
    List<A> Items = new List<A>();
}

I have a class called Bar that can save and load lists of objects of type B: 我有一个名为Bar的类,可以保存和加载B类对象的列表:

class Bar {
    void Save(List<B> ComplexItems);
    List<B> Load();
}

B is a subclass of A. Foo, Bar, A and B are in a library and the user can create children of any of the classes. B是A的子类.Foo,Bar,A和B都在库中,用户可以创建任何类的子代。

What I would like to do is something like the following: 我想做的是如下:

Foo MyFoo = new Foo();
Bar MyBar = new Bar();

MyFoo.Items = MyBar.Load();
MyBar.Save(MyFoo.Items);

Obviously this won't work. 显然这不起作用。 Is there a clever way to do this that avoids creating intermediate lists? 是否有一种聪明的方法可以避免创建中间列表?

thanks, Andy 谢谢,安迪

使用.NET 4.0和IEnumerable<T>而不是List<T>http://blogs.msdn.com/b/csharpfaq/archive/2010/02/16/covariance-and-contravariance-faq.aspx ),否则在TSave泛型(列表项类型)。

If you can change your save function to take an IEnumerable then you can : 如果您可以更改保存功能以获取IEnumerable,那么您可以:

void Save(IEnumerable<B> ComplexItems);
Save(MyFoo.Items.Cast<B>());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM