h-r*_*rai 1 c# setter struct immutability
我正在读一本书,发现结构实际上是不可变的对象.但他们有吸气剂和制定者.我想知道结构的属性是否可以在创建后更改.
public struct Test
{
public string str {get; set; }
public int int1 {get; set; }
}
Run Code Online (Sandbox Code Playgroud)
'str'和'int1'的值一旦被赋值,是否可以更改?
结构可以是可变的也可以是不可变的,但根据许多人的说法它们应该是不可变的.
你的例子是一个可变的结构.
使用示例:
var t = new Test();
// t.str is null, and t.int1 is 0
t.str = "changed!"; // OK
var t2 = t;
t2.int1 = 42;
// t.int1 is still 0
var li = new List<Test> { t, t2, };
t.int1 = 666; // OK, but copy in li is unaffected
li[0].int1 = 911; // compile-time error, not a variable
var t3 = t2;
bool checkA = (t3 == t2); // compile-time error, you did not overload operator ==
bool checkB = t3.Equals(t2); // OK, true, ValueType class overrides Equals for you
bool checkC = t2.Equals(t); // OK, false
bool checkD = object.ReferenceEquals(t, t); // false, two distinct boxes
// same as (object)t==(object)t
Run Code Online (Sandbox Code Playgroud)
根据请求,这是一种使struct不可变的方法:
public struct Test
{
public string str { get; private set; }
public int int1 { get; private set; }
public Test(string str, int int1) : this()
{
this.str = str;
this.int1 = int1;
}
}
// if you introduce methods (other than constructors) that use the private setters,
// the struct will no longer be immutable
Run Code Online (Sandbox Code Playgroud)
这是另一个:
public struct Test
{
readonly string m_str;
readonly int m_int1;
public string str { get { return m_str; } }
public int int1 { get { return m_int1; } }
public Test(string str, int int1)
{
m_str = str;
m_int1 = int1;
}
}
Run Code Online (Sandbox Code Playgroud)