2011-08-16 10 views
5

불변 및 변경 가능 유형 간의 차이를 보여주기 위해 빠른 스 니펫을 작성하려고합니다. 이 코드가 여러분에게 모두 올바른 것처럼 보입니까?불변 및 변경 가능 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!"); 
    } 
} 
+0

그것은 변경할 수있는 클래스가 아니라 필드입니다. 'readonly' 필드가 생성자 코드 나 초기화시에만 할당되는 한, 클래스에서'readonly'와'normal' 필드를 섞을 수 있습니다. – Matten

+0

'ImmutableTypeExample MakeTestFoo()'는별로 의미가 없습니다. 그것은 정적이라고 생각합니까? –

답변

14

그래, 맞아.

그러나 나는 "leaky"mutability에 대해 이야기합니다. 예를 들어 :

public class AppearsImmutableButIsntDeeplyImmutable 
{ 
    private readonly StringBuilder builder = new StringBuilder(); 
    public StringBuilder Builder { get { return builder; } } 
} 

나는 인스턴스가 나타납니다 빌더를 변경할 수 없습니다,하지만 난 할 수

value.Builder.Append("hello"); 

당신이 kinds of immutability 에릭 Lippert의 블로그 게시물을 읽을 가치가있을 것입니다 - 그리고 참으로 시리즈의 모든 나머지 게시물.

+0

즉,이 예제는 사용하는 문자열 속성도 변경되지 않기 때문에 작동합니다. 변경할 수있는 속성을 가진 경우 getter를 통해서만 사용할 수 있다고하더라도 완전히 변경할 수는 없습니다. –

+0

당신은 또한 콜렉션, 불변/변경 가능 클래스 쌍 등에 대해서도 생각할지도 모른다. 나는이 문맥에서 흥미로운 것이어야한다는 기사를 썼다 : http://rickyhelgesson.wordpress.com/2012/07/17/mutable-or- 불변의 세계에서/ –

4

네, 맞습니다.

private 멤버는 클래스가 변경되지 않도록 읽기 전용 일 필요는 없으며, 이는 클래스 내부의 추가적인 예방책 일뿐입니다.

+0

팁 주셔서 감사합니다 – Hoody

관련 문제