在结构中分配字段/属性

soa*_*dos 10 c# struct variable-assignment

可能重复:
修改Dictionary中的Struct变量

为什么会这样

  MyStruct test = new MyStruct();
  test.Closed = true;
Run Code Online (Sandbox Code Playgroud)

效果很好,但是

MyDictionary[key].Closed = true;
Run Code Online (Sandbox Code Playgroud)

在编译时显示"无法修改表达式,因为它不是变量"错误?

为什么这两种情况下的任务有所不同?

注意:MyDictionary属于类型<int, MyStruct>

结构代码:

public struct MyStruct
{
    //Other variables
    public bool Isclosed;
    public bool Closed
    {
        get { return Isclosed; }
        set { Isclosed = value; }
    }
//Constructors
}
Run Code Online (Sandbox Code Playgroud)

Kei*_*ith 12

因为MyDictionary[key]返回一个结构,它实际上是在集合中返回对象的副本,而不是在使用类时发生的实际对象.这是编译器警告你的内容.

要解决这个问题,你必须重新设置MyDictionary[key],也许是这样的:

var tempObj = MyDictionary[key];
tempObj.Closed = true;
MyDictionary[key] = tempObj;
Run Code Online (Sandbox Code Playgroud)

  • @soandos 结构在方法之间传递时总是被复制,因此“整个构造函数”一直在发生(例如,当您通过该字典中的键访问结构时),这就是为什么建议不要让结构大于 16 个字节 (3认同)