为什么能结构改变自己的领域? [英] Why can struct change their own fields?
问题描述
考虑美孚结构如下:
struct Foo
{
public float X;
public float Y;
public Foo(float x, float y)
{
this.X = x;
this.Y = y;
}
public void Change(float x)
{
this.X = x;
}
}
我理解修改在构造方面,那是完全合乎逻辑的,我和我的结构作为超值,喜欢数<击>一成不变击>类型的理解。
然而,由于人们可以<击>'T 击>做的:
However, since one can't do:
Foo bar = new Foo(1, 2);
bar.X = 5;
为什么可以一用:
Why can one use:
Foo bar = new Foo(1, 2);
bar.Change(5);
修改:如果结构是可变的,那么为什么他们不能被修改的列表时,或从属性返回
EDIT: If structs are mutable, then why can't they be modified when in a list or returned from a property?
<一个href=\"http://stackoverflow.com/questions/749869/cannot-modify-ex$p$pssion-because-it-is-not-a-variable\">Cannot修改前pression,因为它不是一个可变
推荐答案
您已经有了一个关键的错误的假设。
You've made a key mistaken assumption.
.NET结构是可变的。您可以绝对执行 bar.X = 5;
.NET structs are mutable. You can absolutely perform bar.X = 5;
.
您应该设计结构是不变的,而是由code您提供,他们是可变的。
You should design structs to be immutable, but by the code you have provided, they are mutable.
看一看这个问题,为在那里可变结构可以让你陷入困境的描述。
结构的不变性
Have a look at this question for a description of where mutable structs can get your into trouble. Immutability of structs
这篇关于为什么能结构改变自己的领域?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!