【发布时间】:2018-10-29 07:59:01
【问题描述】:
假设我有一个带有公共 int 的 x 和 y 的结构点。我想改变一个值,我可以。但是一旦我将它存储在字典中,我就不能再这样做了。为什么?
MWE:
using System;
using System.Collections.Generic;
public class Program
{
public struct Point
{
public int x, y;
public Point(int p1, int p2)
{
x = p1;
y = p2;
}
}
public static void PrintPoint(Point p)
{
Console.WriteLine(String.Format("{{x: {0}, y: {1}}}", p.x, p.y));
}
public static void Main()
{
var c = new Point(5, 6);
PrintPoint(c); // {x: 5, y: 6}
c.x = 4; // this works
PrintPoint(c); // {x: 4, y: 6}
var d = new Dictionary<string, Point>()
{
{ "a", new Point(10, 20) },
{ "b", new Point(30, 40) }
};
foreach (Point p in d.Values)
{
PrintPoint(p); // this works
}
PrintPoint(d["a"]); // this works // {x: 10, y: 20}
Console.WriteLine(d["a"].x.ToString()); // this works // 10
// d["a"].x = 2; // why doesn't this work?
}
}
为什么我可以访问字典中的结构变量但不能再更改它们?如何更改它们?
【问题讨论】:
-
因为
d["a"]返回一个您没有存储在任何地方的临时副本。修改一个临时的没有意义 -
它“不起作用”,因为编译器会抱怨。该投诉的内容是相关的。
-
解决此问题的一种方法是为字典项分配一个新的
Point和新的x值和相同的y值:d["a"] = new Point(2, d["a"].y); -
从设计的角度来看一个评论:如果您将拥有一个构造函数,该构造函数接受用于设置属性(或本例中的字段)的值,这对您的客户很有帮助class/struct 使构造函数参数名称与属性名称相同,以便他们了解他们正在设置的内容。例如:
public Point(int x, int y) { ... }
标签: c#