gpt4 book ai didi

c# - 更改集合中的结构

转载 作者:太空狗 更新时间:2023-10-30 00:53:34 25 4
gpt4 key购买 nike

我在 Richter 的书中读到了关于拳击的内容,但有一件事我不明白。
我已成功更改对象中的 struct。但是当我尝试更改集合中的 struct 时,我遇到了问题。

//my struct
internal struct Point:IChangeBoxedPoint
{
public Int32 x, y;
public void Change(Int32 x, Int32 y)
{
this.x = x;
this.y = y;
}

public override string ToString()
{
return String.Format("{0}, {1}", this.x, this.y);
}
}

public static void Main()
{
List<Point> a = new List<Point>();
Point p = new Point();
p.Change(1, 1);
Console.WriteLine(p); //write 1, 1
object o = p;
Console.WriteLine(o); //write 1, 1
((Point)o).Change(2, 2);
Console.WriteLine(o); //write 1, 1
((IChangeBoxedPoint)o).Change(3, 3);
Console.WriteLine(o); //write 3, 3
for (int i = 0; i < 10; i++)
{
p.x = p.y = i;
a.Add(p);
}

Console.WriteLine(a[0]); //write 0, 0
((IChangeBoxedPoint)a[0]).Change(300,300);
Console.WriteLine(a[0]); //still writes 0,0
}

最佳答案

您应该将您的收藏声明为 List<IChangeBoxedPoint>而不是 List<Point> .

如果您将列表声明为 List<Point>然后你的值被装箱/取消装箱到界面,正如其他人已经说过的那样。但是,如果您有一个接口(interface)列表,那么只有当您将它们添加到列表中时,值才会被装箱,从而允许您根据需要更改它们。

关于c# - 更改集合中的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15805386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com