c#参考列表
本文关键字:列表 参考 | 更新日期: 2023-09-27 18:02:03
我想知道:如何向列表中添加新成员,以便当我改变变量的值时也会改变列表。
例如:int a=4;
list<int> l=new list<int>();
l.Add(a);
a=5;
foreach(var v in l)
Console.WriteLine("a="+v);
输出:= 4
谢谢
你需要使用引用类型。
对于值类型,例如int
,您将获得列表中变量的副本,而不是引用的副本。
这对值类型变量列表不起作用,每次更改值类型变量时,您都会在堆栈中获得一个新的变量值副本。因此,一个解决方案是使用某种引用类型包装器。
class NumericWrapper
{
public int Value { get; set; }
}
var items = new List<NumericWrapper>();
var item = new NumericWrapper { Value = 10 };
items.Add(item);
// should be 11 after this line of code
item.Value++;
您可以构建一个包装器容器,然后根据需要更新包装器的值。如下所示,例如:
//item class
public class Item<T>
{
T Value {get;set;}
}
//usage example
private List<String> items = new List<string>();
public void AddItem( Item<string> item)
{
items.Add(item);
}
public void SetItem(Item<T> item,string value)
{
item.Value=value;
}
必须将int括在引用类型中。
试试这个:
internal class Program
{
private static void Main(string[] args)
{
IntWrapper a = 4;
var list = new List<IntWrapper>();
list.Add(a);
a.Value = 5;
//a = 5; //Dont do this. This will assign a new reference to a. Hence changes will not reflect inside list.
foreach (var v in list)
Console.WriteLine("a=" + v);
}
}
public class IntWrapper
{
public int Value;
public IntWrapper()
{
}
public IntWrapper(int value)
{
Value = value;
}
// User-defined conversion from IntWrapper to int
public static implicit operator int(IntWrapper d)
{
return d.Value;
}
// User-defined conversion from int to IntWrapper
public static implicit operator IntWrapper(int d)
{
return new IntWrapper(d);
}
public override string ToString()
{
return Value.ToString();
}
}