2012-11-19 2 views
-2

가능한 복제를 설정하는 동안 : 나는 정적 속성을 설정하려고 할 때
New to C#, why does Property Set throw StackOverflow exception?스택 오버플로 예외 정적 속성 C 번호를

나는 스택 오버플로 예외를 받고 있어요.

public static class StaticTest 
{ 
    static string stringToSet 
    { 
     get 
     {     
      return stringToSet; 
     } 
     set 
     { 
      stringToSet = value; 
     } 
    } 
} 

그런 다음, 다른 클래스 : 내가 잘못

public void setStaticProperty() 
{ 
    StaticTest.stringToSet = "Hello World"; // StackOverflow exception here 
} 

을하고있어 무엇? 이 StackOverflow에 따라서, 자신을 호출하기 때문에

+1

속성 설정자가 자신을 보조 필드 또는 자동 속성 – MMK

+0

으로 호출하기 때문에 스택 오버플로가 발생합니다. –

+2

참조 http://stackoverflow.com/questions/13454902/stack-overflow-exception-while-setting-static-property-c-sharp –

답변

8
set 
    { 
     stringToSet = value; 
    } 

당신은 (그 문제에 대한 및 게터) 당신의 세터의 무한 재귀를 얻었다.

직접 기본 필드를 수정할 필요가없는 경우, 대신 자동 재산 사용 : 정적 속성 setter에서

static string stringToSet {get; set;} 
3

을, 당신은 호출하는 정적 속성 stringToSet,에 값을 할당하는 static property setter를 호출하는 static property setter를 호출하는 static property stringToSet에 값을 할당하는 static property setter입니다. static property setter를 호출하면 (자), 정적 property setter를 호출하는 정적 property stringToSet에 값을 할당합니다. 정적 속성 stringToSet ...

속성 값을 저장할 개인 필드를 추가해야합니다. 대개 대문자 (StringToSet)로 시작하도록 속성 이름을 바꿉니다.

private string stringToSet; 

public string StringToSet { 
    get { 
     return stringToSet; 
    } 
    set { 
     stringToSet = value; 
    } 
} 
+0

안녕하세요, 답변에 많은 감사드립니다. 하지만 이걸로 정적 속성을 가지고 있지 않습니다. – Guilherme

+0

@Guilherme : 죄송합니다. 필드와 속성을 모두 '정적'으로 표시하면 정적 속성과 동일하게 작동한다는 것을 잊어 버렸습니다. 하지만 당신이 이미 당신의 대답을 찾은 것을 봅니다. –