0

Assuming I have a class like this:

class Base { }
class A : Base { }
class B : Base { }
class C : Base { }

And objects like this:

A a = new A();
List<B> bs = new List<B>();
List<C> cs = new List<C>();

Is it possible to create a new list containing references to the other lists (So that changes are reflected in the original items? Such as:

void modifyContents(List<Base> allItems) {
  //modify them somehow where allItems contains a, bs and cs
}
4

2 回答 2

3

您不能添加/删除/替换其他列表中的项目,但可以修改其他列表中的项目。

List<Base> baseList = new List<Base>();
baseList.Add(a);
baseList.AddRange(bs);
baseList.AddRange(cs);
// now you can modify the items in baseList
于 2012-04-13T20:00:12.947 回答
2
  1. 使用 LINQ Concat()将两个列表连接到一个列表中IEnumerable<Base>
  2. List<Base>然后通过传入之前加入的构造函数创建一个新实例

样本

class Base
{
     public string Id { get; set; }
}

List<B> bs = new List<B>() { new B() };
List<C> cs = new List<C> { new C(), new C() };
var common = new List<Base>(bs.OfType<Base>().Concat(cs.OfType<Base>()));

// bs[0] will be updated
common[0].Id = "1";

// cs[0] will be updated
common[1].Id = "2";

// cs[1] will be updated
common[2].Id = "3";
于 2012-04-13T20:04:47.873 回答