这个问题在这里已经有了答案:
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
是结构,结构是值类型,当您通过方法、属性或索引器访问它时,它返回结构实例的副本而不是实例本身。尝试声明 Key
如class
.有关详细信息,您可以搜索结构和类或值和引用类型之间的差异。
https://stackoverflow.com/questions/19151599/