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

标签 c# list reference

如何通过引用 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/

相关文章:

python - 将 pandas 列表列转换为矩阵表示(一次热编码)

c++ - const T*& 和 const T* 不会在函数重载时产生歧义

C#:如何让用户控件正确地自动调整自身大小

c# - 将自定义验证添加到 ASP.NET Core 的 JWT token ?

c# - sealed 关键字会影响编译器对强制转换的看法

c# - 列表 'Except' 比较 - 忽略大小写

python - 按多个字符将列表拆分为 block [Python]

python - 按值复制变量而不是引用

c++ - “new Foo()” 和 “&Foo()” 作为参数的区别

c# - 如何使用 .net webBrowser 对象