简体   繁体   English

通过引用List.Add()传递值

[英]Passing a value by reference to List.Add()

How could I pass a value by reference to the List ? 如何通过引用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);

My objective is elements on the list to be related with the previous ones. 我的目标是将列表中的元素与先前的元素相关联。 In C++ I would use a list of pointers, however right now I feel hopeless. 在C ++中,我将使用一个指针列表,但是现在我感到绝望了。

You can't do it with value types.You need to use a reference type. 不能使用值类型。您需要使用引用类型。

(change) You can't do it with object too, you need to define your custom class which has a int property. (更改)您也无法使用object进行操作,您需要定义具有int属性的自定义类。 If you use object it will be automatically perform boxing and unboxing.And actual value never affected. 如果使用对象,它将自动执行装箱和拆箱。实际值不会受到影响。

I mean something like this: 我的意思是这样的:

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; }
}

ints are primitives, so you are not passing around a pointer,but the value it self. int是基元,因此您不需要传递指针,而是传递它自己的值。

Pointers are implicit in C#,so you can wrap ints in an object and pass that object around instead and you will be passing a pointer to the object. 指针在C#中是隐式的,因此您可以将int包装在一个对象中,然后将该对象传递给它,您将传递一个指向该对象的指针。

You can't store value types in a .NET generic collection and access them by reference. 您不能将值类型存储在.NET通用集合中,也不能通过引用访问它们。 What you could do is what Simon Whitehead suggested. 你能做的是西蒙·怀特海德的建议。

I see few solutions of this problem: 我看到此问题的几种解决方案:

1) Create a class which will hold the integer (and possibly other values you might need) 1)创建一个将容纳整数(以及您可能需要的其他值)的类

2) Write "unsafe" code. 2)编写“不安全”代码。 .NET allows usage of pointers if you enable this for your project. 如果为项目启用了.NET,则允许使用指针。 This might even require creating custom collection classes. 这甚至可能需要创建自定义集合类。

3) Restructure your algorithm to not require references. 3)重组算法,使其不需要引用。 Eg save indexes of values you wish to change. 例如,保存要更改的值的索引。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM