gpt4 book ai didi

c# - 通过引用传递值到 List.Add()

转载 作者:太空宇宙 更新时间:2023-11-03 20:09:30 25 4
gpt4 key购买 nike

如何通过引用 List 来传递值?

int x = 2;
List<int> newList = new List<int>();
newList.Add(x);

System.Console.WriteLine(x);
x = 7;
System.Console.WriteLine(newList[0]);
newList[0] = 10;
System.Console.WriteLine(x);

我的目标是列表中的元素与之前的元素相关联。在 C++ 中,我会使用指针列表,但现在我感到绝望。

最佳答案

你不能用值类型来做。你需要使用引用类型。

(改变)你也不能用对象来做,你需要定义你的自定义类,它有一个 int 属性。如果您使用对象,它将自动执行装箱和拆箱。实际值不受影响。

我的意思是这样的:

MyInteger x = new MyInteger(2);
List<MyInteger> newList = new List<MyInteger>();
newList.Add(x);

Console.WriteLine(x.Value);
x.Value = 7;
Console.WriteLine(newList[0].Value);
newList[0].Value = 10;
Console.WriteLine(x.Value);

class MyInteger
{
public MyInteger(int value)
{
Value = value;
}
public int Value { get; set; }
}

关于c# - 通过引用传递值到 List.Add(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21008760/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com