2010-07-02 1 views
3

PRISM 툴킷을 검토해 봤는데 빈 getter/setter가있는 공용 속성을 선언하지만 아직 인스턴스화 된 클래스의 속성을 설정할 수있는 많은 예제가 있습니다. 어떻게/왜 가능합니까?C#에서 아무 것도 설정하지 않은 속성을 설정할 수있는 이유는 무엇입니까?

public class ShellPresenter 
    { 
     public ShellPresenter(IShellView view) 
     { 
      View = view; 

     } 

     public IShellView View { get; private set; } 
    } 

//calling code 
ShellPresenter sp = new ShellPresenter(); 

//Why is this allowed? 
    sp.View = someView; 

답변

8

그들은 C# 자동 속성을 사용하고 있습니다. 이것은 컴파일러가 여러분을 위해 뒷받침 필드를 생성하는 편리함입니다. private set은 속성이 클래스 외부에서 읽기 전용임을 의미합니다. 따라서 sp.View = someView;을 클래스 외부에서 사용하면 컴파일러 오류가 발생합니다. 객체가 클래스 자체 내에서 설정되는 경우를 제외하고는 게시 무엇 Red Gate .NET Reflector

public class ShellPresenter 
{ 
// Fields 
[CompilerGenerated] 
private IShellView <View>k__BackingField; 

// Methods 
public ShellPresenter(IShellView view) 
{ 
    this.View = view; 
} 

// Properties 
public IShellView View 
{ 
    [CompilerGenerated] 
    get 
    { 
     return this.<View>k__BackingField; 
    } 
    [CompilerGenerated] 
    private set 
    { 
     this.<View>k__BackingField = value; 
    } 
    } 
} 
+0

응답 해 주셔서 감사합니다. 컴파일러가 뒷받침 필드를 생성한다는 대답에 감사드립니다. "무슨 일이 일어나는가"를 아는 것이 도움이됩니다. 나는 그들이 그들이하는 일에 명시 적이지 않고 첫 번째 사이트에서 혼란 스럽기 때문에 필연적으로 좋아한다는 것을 알지 못합니다. 나는 그들의 목적을 본다. –

-1

C# 컴파일러는 사용자를 위해 백엔드 필드를 생성합니다. 이 구문은 익명 형식 지원 (예 : new { A = 1, B = "foo" })에 대해 도입되었습니다.

+7

익명 유형과 관련된 자동 등록 정보는 무엇입니까? –

+2

자동 속성은 익명 형식과 관련이 없습니다. –

+0

@Sam excellent question n –

0

디 컴파일. 다음은 허용되는 것과 허용되지 않는 것의 코드 샘플입니다.

public interface IShellView 
    { 

    } 
    public class View:IShellView 
    { 
    } 

    //public class SomeOtherClass 
    //{ 
    // static void Main() 
    // { 
    //  IShellView someView = new View(); 
    //  //calling code 
    //  ShellPresenter sp = new ShellPresenter(); 

    //  //Why is this allowed? 
    //  sp.View = someView;//setting a private set outside the ShellPresenter class is NOT allowed. 
    // } 
    //} 

    public class ShellPresenter 
    { 
     public ShellPresenter() 
     { 
     } 
     public ShellPresenter(IShellView view) 
     { 
      View = view; 

     } 
     static void Main() 
     { 
      IShellView someView = new View(); 
      //calling code 
      ShellPresenter sp = new ShellPresenter(); 

      //Why is this allowed? 
      sp.View = someView;//because now its within the class 
     } 
     public IShellView View { get; private set; } 
    } 
+0

Decompiling이 항상 답이되는 것은 아닙니다. –

+0

@Henk, "why/how"질문의 경우 디 컴파일이 대답입니다. 디 컴파일 된 버전은 자동 속성으로 어떤 일이 일어나고 있는지 파악하는 데 도움이 될 수 있습니다. "empty getters/setters"가 사용될 때 실제로 필드가 수정되고 리턴되는 것을 보여줍니다. – statenjason

0

와 ShellPresenter이 허용되지 않습니다

관련 문제