c# - 为什么这一行代码与上面两行不同?

这个问题在这里已经有了答案:





Modify Struct variable in a Dictionary

(4 个回答)


8年前关闭。




请参阅注释代码中的问题...

public struct Key
{
    public string Name;
    public object Value;
}


public class PrimaryKey
{
    Dictionary<string, Key> _keys = new Dictionary<string, Key>();

    object this[string index]
    {
        get
        {
            return _keys[index].Value;
        }
        set
        {
            if (!_keys.ContainsKey(index))
                _keys.Add(index, new Key() { Name = index, Value = value });
            else
            {
                var k = _keys[index];        // This compiles
                k.Value = value;             // just fine.

                _keys[index].Value = index;  // So why wouldn't this?
            }
        }
    }
}

我得到错误:

Cannot modify the return value of Dictionary<string,Key>.this[string] because it is not a variable

最佳答案

由于Key是结构,结构是值类型,当您通过方法、属性或索引器访问它时,它返回结构实例的副本而不是实例本身。尝试声明 Keyclass .有关详细信息,您可以搜索结构和类或值和引用类型之间的差异。

https://stackoverflow.com/questions/19151599/

相关文章:

file - 处理时output.println()中的错误

twitter-bootstrap - 导航栏中的两行,一列跨越两行

generics - Ada : invalid prefix in selected compon

c# - 编译器不一致的可访问性错误,将嵌套类作为函数参数传递

compiler-errors - 模式匹配Erlang?

objective-c - 使用typedef枚举时,返回类型枚举EnumName返回枚举成员时会产

compiler-errors - 为自定义MATLAB工具箱执行编译器脚本时出错

objective-c - 错误Maddage : expected expression? [du

compiler-errors - 编译器无法识别显式类型

c# - NHibernate错误:s