불변 및 변경 가능 유형 간의 차이를 보여주기 위해 빠른 스 니펫을 작성하려고합니다. 이 코드가 여러분에게 모두 올바른 것처럼 보입니까?불변 및 변경 가능 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()'는별로 의미가 없습니다. 그것은 정적이라고 생각합니까? –