我想知道:如何將新成員添加到列表中,以便當我更改變量的值時也會更改列表。c#refrencecing list
例如:
int a=4;
list<int> l=new list<int>();
l.Add(a);
a=5;
foreach(var v in l)
Console.WriteLine("a="+v);
輸出: A = 4
感謝
我想知道:如何將新成員添加到列表中,以便當我更改變量的值時也會更改列表。c#refrencecing list
例如:
int a=4;
list<int> l=new list<int>();
l.Add(a);
a=5;
foreach(var v in l)
Console.WriteLine("a="+v);
輸出: A = 4
感謝
你需要,如果你想這樣的事情發生使用引用類型。
對於值類型,例如int
,您會在列表中獲得變量的副本,而不是引用的副本。
請參閱MSDN上的Value Types and Reference Types。
這不適用於值類型變量的列表,每當您更改值類型變量時,您將在堆棧中獲得新的變量值副本。所以一個解決方案會使用某種引用類型的包裝器。
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();
}
}