2013-04-20 4 views
3

추상 클래스의 정적 메서드에서 현재 클래스의 형식 (이름 문자열은 아니지만 형식 자체)을 어떻게 얻을 수 있습니까?정적 메서드에서 런타임에 현재 클래스 가져 오기?

using System.Reflection; // I'll need it, right? 

public abstract class AbstractClass { 

    private static void Method() { 

     // I want to get CurrentClass type here 

    } 

} 

public class CurrentClass : AbstractClass { 

    public void DoStuff() { 

     Method(); // Here I'm calling it 

    } 

} 

이 질문은 이것과 매우 유사하다 :

How to get the current class name at runtime?

그러나, 나는 정적 메서드 내부에서이 정보를 얻을 싶어요.

+0

같은 'System.Diagnostics.StackTrace'를 사용할 수 있습니다 파생 클래스에서 정적 방법 : [GetType을 정적 방법 (http://stackoverflow.com/questions/7839691/gettype- 정적 방법으로) – Zbigniew

답변

3
public abstract class AbstractClass 
{ 
    protected static void Method<T>() where T : AbstractClass 
    { 
     Type t = typeof (T); 

    } 
} 

public class CurrentClass : AbstractClass 
{ 

    public void DoStuff() 
    { 
     Method<CurrentClass>(); // Here I'm calling it 
    } 

} 

당신은 단순히 기본 클래스에 제네릭 형식 인수로 유형을 전달하여 정적 메서드에서 파생 된 유형에 액세스 할 수 있습니다.

+0

그래, 나는 그동안 제네릭을 사용하려고 생각 해왔다. –

+2

그런 제네릭을 사용한다면'ExtendedClass : CurrentClass'를 가지고 있다면 어떤 일이 일어날 지 생각해보십시오 :'Method'는'ExtendedClass'가 아니라'CurrentClass'를 얻을 것입니다. –

0

를 참조하십시오. 이 작업을 수행 할 수 있습니다 :이 호출하는 경우

public abstract class AbstractClass { 
    protected static void Method<T>() { 
     Method(typeof(T)); 
    } 
    protected static void Method(Type t) { 
     // put your logic here 
    } 
    protected void Method() { 
     Method(GetType()); 
    } 
} 
1

: 당신은 또한 static 컨텍스트에서 액세스 할 수 있도록 필요한 경우

public abstract class AbstractClass { 
    protected void Method() { 
     var t = GetType(); // it's CurrentClass 
    } 
} 

, 당신은 과부하, 심지어 일반적인 과부하, 예를 추가 할 수 있습니다 단지 당신이 한 번 봐

abstract class A 
{ 
    public abstract string F(); 
    protected static string S() 
    { 
     var st = new StackTrace(); 
     // this is what you are asking for 
     var callingType = st.GetFrame(1).GetMethod().DeclaringType; 
     return callingType.Name; 
    } 
} 

class B : A 
{ 
    public override string F() 
    { 
     return S(); // returns "B" 
    } 
} 

class C : A 
{ 
    public override string F() 
    { 
     return S(); // returns "C" 
    } 
} 
관련 문제