0

根据List(T)http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx的文档,一个集合支持多个阅读器。只要集合不被修改。

我的问题是什么时候修改集合?

  • 当我更改列表中的值时?例如一个List<int>intList[0] = 1;
  • 当我添加/删除列表中的某些内容时?例如,intList.add(1);

谢谢你的帮助。

保罗

4

2 回答 2

2

对于列表,当您从数组中添加或删除元素或更改元素的内容时,它被视为已修改,因此您的两个示例都确实“修改”了集合。

但作为旁注:对于数组,在这种情况下,您实际上无法“修改”集合。

所以我们在List<T>T 和一个普通数组之间的行为上有明显的区别。

例如,此代码引发异常:

var testList = Enumerable.Range(1, 10).ToList();

foreach (var i in testList)
{
    testList[0] = 1;
}

但是这段代码不会抛出异常:

var testArray = Enumerable.Range(1, 10).ToArray();

foreach (var i in testArray)
{
    testArray[0] = 1;
}

更改存储在元素中的引用类型的属性

请注意,如果您有一个引用类型的列表,并且您更改了列表元素之一的属性之一,这不算作修改集合。

例如,给定这个类:

class Element
{
    public int Value
    {
        get;
        set;
    }
}

以下代码不会引发异常:

List<Element> list = new List<Element>()
{
    new Element(),
    new Element()
};

foreach (var element in list)
{
    list[0].Value = 1;
}

它不被视为修改集合的原因是您没有更改元素的内容,因为引用本身保持完全相同。

于 2013-09-27T07:48:49.700 回答
2

我的问题是什么时候修改集合?

当我更改列表中的值时?例如一个List<int>, intList[0] = 1;

Yes, changing the item does change the collection.

However, when your T from List<T> is a reference type, and you don't change the entire object (e.g. change only one class property value) the collection is not modified. e.g. consider a class Foo with int property Bar.

List<Foo> items = new List<Foo> { new Foo(), new Foo() };

Following code does modify the collection:

items[0] = new Foo();

And following does not modify the collection:

items[0].Bar = 10;

When I add/delete something of the list? For example, intList.add(1);

It always modifies the collection.

于 2013-09-27T08:09:22.220 回答