我想寫一個快速片段展示的可變和不可變類型之間的區別。 這段代碼是否適合你?永恆VS易變的C#
class MutableTypeExample
{
private string _test; //members are not readonly
public string Test
{
get { return _test; }
set { _test = value; } //class is mutable because it can be modified after being created
}
public MutableTypeExample(string test)
{
_test = test;
}
public void MakeTestFoo()
{
this.Test = "FOO!";
}
}
class ImmutableTypeExample
{
private readonly string _test; //all members are readonly
public string Test
{
get { return _test; } //no set allowed
}
public ImmutableTypeExample(string test) //immutable means you can only set members in the consutrctor. Once the object is instantiated it cannot be altered
{
_test = test;
}
public ImmutableTypeExample MakeTestFoo()
{
//this.Test = "FOO!"; //not allowed because it is readonly
return new ImmutableTypeExample("FOO!");
}
}
這並不是說是可變的,但現場的類。只要只在構造函數代碼中或初始化時分配'readonly'字段,就可以在類中混合「只讀」和「正常」字段。 – Matten
'ImmutableTypeExample MakeTestFoo()'沒有多大意義。它應該是靜態的嗎? –