不変型と可変型の違いを説明するための簡単なスニペットを作成しようとしています。 このコードはあなたにすべて正しいと思われますか?不変型と変更可能な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'フィールドがコンストラクタコードや初期化時にのみ割り当てられている限り、クラス内で' readonly'と 'normal 'フィールドを混在させることができます。 – Matten
'ImmutableTypeExample MakeTestFoo()'はあまり意味がありません。それは静的であると思われますか? –