我从诸如“Is it Possible to store references to objects in list?”这样的问题中了解到,您可以在不从列表中删除对象的情况下修改对象的属性。所以你可以制作一个包装类并将你的对象放入其中,然后修改值。但是,如果您要做的是更改对象本身...
我想知道的是:你能否制作一系列对象,将它们存储在类似结构的列表中,然后从列表或对象中访问它们?你能让object 和 object-in-the-list 表现得像它们是同一个对象吗?如果你使用数组,你能做到这一点吗?
Using System;
Using System.Collections.Generic;
Namespace Project1
{
Class Test
{
Public static void Main()
{
int one = 1;
int two = 2;
int num = 3;
List<int> myList = new List<int>();
myList.Add(one);
myList.Add(two);
myList.Add(num);
myList[2] = 4; // I want this to also set num to 4
num = 5; // I want this to also set myList[2] to 5
Console.WriteLine(myList[2]); //prints 4
Console.WriteLine(num); //prints 5
}
}
}
最佳答案
看了您的代码示例,我想我明白您的意思了。基本上,您想直接 访问数组中的元素,而不是通过索引属性访问器。这样做非常简单,只要数组中的项目是引用类型即可。但是,这不适用于值类型,因为当涉及值类型时,独立变量和索引属性指向不同的内存存储空间。
举例说明:
listOfPersons[2] = new Person { Name = "Homer Simpson", Age = 35 };
Console.WriteLine(listOfPersons[2].Name); // will show Homer Simpson
Person myself = listOfPersons[2];
myself.Name = "Bart Simpson";
Console.WriteLine(myself.Name); // will show Bart Simpson
Console.WriteLine(listOfPersons[2].Name); // will show Bart Simpson
Console.WriteLine(listOfPersons[2].ReferenceEquals(myself)); // will show true
另一方面:
listOfInts[2] = 2;
Console.WriteLine(listOfInts[2]); // will show 2
int myInt = listOfInts[2];
myInt = 5;
Console.WriteLine(myInt); // will show 5
Console.WriteLine(listOfInts[2]); // will show 2...
希望这对您有所帮助!
关于c# - 你能让一个元素和一个列表中的元素表现得像同一个对象吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40391880/