结构体中字段/属性的分配
可能的重复:
修改字典中的结构变量
为什么它
MyStruct test = new MyStruct();
test.Closed = true;
效果很好,但
MyDictionary[key].Closed = true;
显示编译时出现“无法修改表达式,因为它不是变量”错误?
为什么这两种情况下的分配不同?
注意: MyDictionary
的类型为
结构体代码:
public struct MyStruct
{
//Other variables
public bool Isclosed;
public bool Closed
{
get { return Isclosed; }
set { Isclosed = value; }
}
//Constructors
}
Possible Duplicate:
Modify Struct variable in a Dictionary
Why is it that
MyStruct test = new MyStruct();
test.Closed = true;
Works great, but
MyDictionary[key].Closed = true;
Shows a "Cannot modify the expression because it is not a variable" error at compile time?
Why is different about the assignment in these two cases?
Note: MyDictionary
is of type <int, MyStruct>
Code for the struct:
public struct MyStruct
{
//Other variables
public bool Isclosed;
public bool Closed
{
get { return Isclosed; }
set { Isclosed = value; }
}
//Constructors
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
因为
MyDictionary[key]
返回一个结构体,所以它实际上返回集合中对象的副本,而不是使用类时发生的实际对象。这就是编译器警告您的内容。要解决此问题,您必须在对象更改后重新设置
MyDictionary[key]
,可能如下所示:Because
MyDictionary[key]
returns a struct, it is really returning a copy of the object in the collection, not the actual object which is what happens when you use a class. This is what the compiler is warning you about.To work around this, you'll have to re-set
MyDictionary[key]
after the changes to the object, perhaps like this:将结构更改为类......
Change the struct to be a class instead...