在C#中,值类型是可变的还是不可变的? [英] In C# , Are Value types mutable or immutable ?
问题描述
值类型行为表明,我们持有的任何值都无法通过其他变量来更改.
但是我仍然对我在帖子标题中提到的内容感到困惑.有人可以澄清吗?
值类型可以是可变的或(根据某些奇怪的边缘情况进行模数)是不可变的,具体取决于您如何编写它们. >
可变:
public struct MutableValueType
{
public int MyInt { get; set; }
}
不可变:
public struct ImmutableValueType
{
private readonly int myInt;
public ImmutableValueType(int i) { this.myInt = i; }
public int MyInt { get { return this.myInt; } }
}
内置值类型(int
,double
等) 是不可变的,但是您可以非常轻松地创建自己的可变struct
.
一条建议:不要.可变值类型不是一个好主意,应该避免.例如,这段代码是做什么的:
SomeType t = new SomeType();
t.X = 5;
SomeType u = t;
t.X = 10;
Console.WriteLine(u.X);
这取决于.如果SomeType
是值类型,它将显示5
,这是一个非常令人困惑的结果.
请参阅此问题,以获取有关为什么应避免使用可变值类型的更多信息.
Value types behavior shows that whatever value we are holding cannot be changed through some other variable .
But I still have a confusion in my mind about what i mentioned in the title of this post . Can anyone clarify?
Value types can be either mutable or (modulo some weird edge cases) immutable, depending on how you write them.
Mutable:
public struct MutableValueType
{
public int MyInt { get; set; }
}
Immutable:
public struct ImmutableValueType
{
private readonly int myInt;
public ImmutableValueType(int i) { this.myInt = i; }
public int MyInt { get { return this.myInt; } }
}
The built-in value types (int
, double
and the like) are immutable, but you can very easily create your own mutable struct
s.
One piece of advice: don't. Mutable value types are a bad idea, and should be avoided. For example, what does this code do:
SomeType t = new SomeType();
t.X = 5;
SomeType u = t;
t.X = 10;
Console.WriteLine(u.X);
It depends. If SomeType
is a value type, it prints 5
, which is a pretty confusing result.
See this question for more info on why you should avoid mutable value types.
这篇关于在C#中,值类型是可变的还是不可变的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!