【问题标题】:c#: Dictionary TryGetValue creating instance instead of getting referencec#: Dictionary TryGetValue 创建实例而不是获取引用
【发布时间】:2018-02-16 20:07:48
【问题描述】:

我是 C# 的菜鸟,不知道为什么相同的方法以不同的方式工作。我正在制作一个简单的电子表格应用程序,并且正在使用一个单元格字典,其中键是字符串名称,值是 Cell 对象:

public struct Cell
{
    private string Name { get; }
    public Object Content { get; set; }

    public Cell(string n, Object o)
    {
        Name = n;
        Content = o;
    }
}

现在,我需要能够轻松添加/更改单元格的内容,所以我一直在这样做:

Dictionary<string, Cell> cells = new Dictionary<string, Cell>();

//  Assign new cell to 5.0 & print
cells.Add("a1", new Cell("a1", 5.0));
Console.WriteLine(cells["a1"].Content);     //  Writes 5

//  Assign cell to new content & print
cells.TryGetValue("a1", out Cell value);
value.Content = 10.0;
Console.WriteLine(cells["a1"].Content);     //  Writes 5
Console.ReadKey();

当然,字典创建 新单元格就好了,但是当我使用 TryGetValue 时,单元格的新内容并不能成为我想要获取的实际对象。我原以为第二次打印是 10。在调试中,它似乎实例化了一个新的 Cell,而不是获取手头的单元格的引用。

我以前使用过字典,并且使用过 TryGetValue 来更改现有对象的属性。所以这里有两个问题:在这种情况下我做错了什么,以及哪些因素决定了该方法是否返回引用?

【问题讨论】:

  • 你将 Cell 定义为一个结构体。
  • structs 是值类型。因此,您将检索副本而不是参考

标签: c# dictionary reference out trygetvalue


【解决方案1】:

Cellstruct。对于可修改的对象,不建议您使用struct。我想你刚刚发现了原因。

TryGetValue 返回struct 时,它会将其复制到value,这与struct 中的struct 不同。

想象一下,如果您将int(另一种值类型)替换为struct,您是否希望从TryGetValue 分配给int 以更改Dictionary 条目int

如果其他约束要求您使用struct,您需要将cells Dictionary 更新为新的struct,就像您使用任何其他值类型一样:

Dictionary<string, Cell> cells = new Dictionary<string, Cell>();

//  Assign new cell to 5.0 & print
cells.Add("a1", new Cell("a1", 5.0));
Console.WriteLine(cells["a1"].Content);     //  Writes 5

//  Assign cell to new content & print
cells.TryGetValue("a1", out Cell value);
value.Content = 10.0;
cells["a1"] = value;  // update cells Dictionary
Console.WriteLine(cells["a1"].Content);     //  Writes 5
Console.ReadKey();

【讨论】:

  • 完美,当我将 'struct' 替换为 'class' 时,它符合我的期望。我想这里真正的问题是,根据我教授的规范,Cell 是一个结构。我想我可以将 Dictionary 更改为 (其中 Object 是单元格的内容),但这不会首先消除对 Cell 结构的需要吗?有什么见解吗?
【解决方案2】:

您需要将您的struct Cell 变成class Cell

那是因为struct 是一个值类型,它的内容不能通过引用来改变。 如果您想详细了解,可以阅读有关值和引用类型的差异here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-06
    • 2018-11-25
    • 2011-05-10
    • 2014-05-24
    • 2021-09-17
    相关资源
    最近更新 更多