为什么struct可以改变自己的字段? [英] Why can struct change their own fields?
问题描述
按如下方式考虑 Foo 结构:
Consider the Foo struct as follows:
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;
}
}
我理解修改构造函数中的字段,这对我来说是完全合乎逻辑的,而且我将结构体理解为值、类似数字的 immutable 类型.
I understand modifying the field in the constructor, that's perfectly logical to me and my understanding of structs as value, number-like immutable types.
然而,既然人们不能't:
Foo bar = new Foo(1, 2);
bar.X = 5;
为什么可以使用:
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?
推荐答案
您做出了一个关键的错误假设.
You've made a key mistaken assumption.
.NET 结构是可变的.你绝对可以执行 bar.X = 5;
.
.NET structs are mutable. You can absolutely perform bar.X = 5;
.
您应该将结构设计为不可变的,但根据您提供的代码,它们是可变的.
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
这篇关于为什么struct可以改变自己的字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!