2012-08-10 3 views
3

나는 많은 스레드가 이것에 대해 이야기하지만, 지금까지는 내 상황을 직접적으로 돕는 것을 찾지 못했다는 것을 알고 있습니다. 정적 클래스와 비 정적 클래스 모두에서 액세스해야하는 클래스 멤버가 있습니다. 그러나 멤버가 정적이 아닌 경우 정적 메서드에서 멤버를 얻을 수 없습니다.정적 메서드에서 클래스 멤버에 액세스

public class SomeCoolClass 
{ 
    public string Summary = "I'm telling you"; 

    public void DoSomeMethod() 
    { 
     string myInterval = Summary + " this is what happened!"; 
    } 

    public static void DoSomeOtherMethod() 
    { 
     string myInterval = Summary + " it didn't happen!"; 
    } 
} 

public class MyMainClass 
{ 
    SomeCoolClass myCool = new SomeCoolClass(); 
    myCool.DoSomeMethod(); 

    SomeCoolClass.DoSomeOtherMethod(); 
} 

두 가지 방법 중 하나에서 요약을 가져 오는 것이 좋습니다.

+1

정적 멤버는 * Type *에 속합니다. 비 정적 멤버는 해당 유형의 * 인스턴스에 속합니다. – asawyer

+1

'Summary'가 일정해야합니까? 당신은'public const string Summary'를 표시 할 수 있으며, 둘 다에서 액세스 할 수 있습니다. –

답변

8

두 가지 방법 중 하나를 사용하여 요약을 가져 오는 것이 좋습니다.

당신은 myCoolDoSomeOtherMethod에 통과해야합니다 -이 경우 당신이 그것으로 시작하는 인스턴스 메서드해야합니다.

기본적으로 유형 인스턴스의 상태가 필요한 경우 왜 정적으로 만들겠습니까?

+0

귀하의 건설적인 조언을 주셔서 감사합니다. DoSomeOtherMethod를 인스턴스 메서드로 만들고이를 수행하면 불편 함을 덜어 줄 수 있다는 점을 깨달았습니다. – Jeremy

7

정적 메소드에서 인스턴스 구성원에 액세스 할 수 없습니다. 정적 메서드의 핵심은 클래스 인스턴스와 관련이 없다는 것입니다.

0

당신은 그렇게 할 수 없습니다. 정적 메소드는 비 정적 필드에 액세스 할 수 없습니다.

당신은 하나 Summary 정적

public class SomeCoolClass 
{ 
    public static string Summary = "I'm telling you"; 

    public void DoSomeMethod() 
    { 
     string myInterval = SomeCoolClass.Summary + " this is what happened!"; 
    } 

    public static void DoSomeOtherMethod() 
    { 
     string myInterval = SomeCoolClass.Summary + " it didn't happen!"; 
    } 
} 

을 만들 수 있습니다 또는 당신은 DoSomeOtherMethod에 SomeCoolClass의 인스턴스를 전달하고 방금 전달 된 인스턴스에서 Summary를 호출 할 수 있습니다 : 어쨌든

public class SomeCoolClass 
{ 
    public string Summary = "I'm telling you"; 

    public void DoSomeMethod() 
    { 
     string myInterval = this.Summary + " this is what happened!"; 
    } 

    public static void DoSomeOtherMethod(SomeCoolClass instance) 
    { 
     string myInterval = instance.Summary + " it didn't happen!"; 
    } 
} 

난 못해 정말 도달하려는 목표를 확인하십시오.

관련 문제