C# 通过引用将值传递给List.Add()

C# 通过引用将值传递给List.Add(),c#,list,reference,C#,List,Reference,如何通过引用列表传递值 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); intx=2; List newList=新列表(); 新增(x); 系统控制台

如何通过引用
列表
传递值

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);
intx=2;
List newList=新列表();
新增(x);
系统控制台写入线(x);
x=7;
System.Console.WriteLine(newList[0]);
newList[0]=10;
系统控制台写入线(x);

我的目标是清单上的元素与以前的元素相关联。在C++中,我会使用指针列表,但是现在我觉得毫无希望。p> 不能使用值类型。需要使用引用类型

(更改)您不能对object也这样做,您需要定义具有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; }
}
MyInteger x=新的MyInteger(2);
List newList=新列表();
新增(x);
控制台写入线(x.Value);
x、 数值=7;
Console.WriteLine(newList[0].Value);
新建列表[0]。值=10;
控制台写入线(x.Value);
类MyInteger
{
公共MyInteger(int值)
{
价值=价值;
}
公共int值{get;set;}
}

您不能使用值类型。您需要使用引用类型

(更改)您不能对object也这样做,您需要定义具有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; }
}
MyInteger x=新的MyInteger(2);
List newList=新列表();
新增(x);
控制台写入线(x.Value);
x、 数值=7;
Console.WriteLine(newList[0].Value);
新建列表[0]。值=10;
控制台写入线(x.Value);
类MyInteger
{
公共MyInteger(int值)
{
价值=价值;
}
公共int值{get;set;}
}

整数是基本体,因此您传递的不是指针,而是指针本身的值


指针在C#中是隐式的,因此您可以在对象中封装int并传递该对象,这样您将传递一个指向该对象的指针。

int是原语,因此您传递的不是指针,而是指针本身的值


指针在C#中是隐式的,因此您可以在对象中封装int并传递该对象,这样您将传递指向该对象的指针。

您不能在.NET泛型集合中存储值类型并通过引用访问它们。你能做的就是西蒙·怀特黑德的建议

我认为这个问题的解决方案不多:

1) 创建一个包含整数(以及可能需要的其他值)的类

2) 编写“不安全”代码。NET允许在项目中启用指针时使用指针。这甚至可能需要创建自定义集合类


3) 重新构造算法,使其不需要引用。例如,保存要更改的值的索引。

您不能在.NET通用集合中存储值类型并通过引用访问它们。你能做的就是西蒙·怀特黑德的建议

我认为这个问题的解决方案不多:

1) 创建一个包含整数(以及可能需要的其他值)的类

2) 编写“不安全”代码。NET允许在项目中启用指针时使用指针。这甚至可能需要创建自定义集合类


3) 重新构造算法,使其不需要引用。例如,保存您希望更改的值的索引。

您可以将其作为
对象的列表,并让它们在进入时装箱?不管怎么说,这似乎是一个非常糟糕的主意。类是引用类型。只需声明一个属性类型为int.Easy-peasy的类。@SimonWhitehead我试过了,但对象不可能。因为装箱和拆箱是自动执行的。实际值永远不会改变。我并没有认真阅读整个问题。对我来说太早了:(你可以把它列成一个
对象的列表,让它们在进入时被装箱?)这似乎是一个非常糟糕的主意。类是引用类型。只需声明一个属性为int.Easy peasy的类。@SimonWhitehead我试过了,但对象不可能。因为装箱和拆箱是自动执行的。实际值nevChanger很好。我没有真正阅读整个问题。对我来说太早了:(我想知道你是如何得到输出的,因为
List newList=newList()
甚至没有编译。我想知道你是如何得到输出的,因为
List newList=newList()
甚至没有编译。