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)
| 归档时间: |
|
| 查看次数: |
10483 次 |
| 最近记录: |