2013-04-20 60 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

看看這個靜態方法:[中的GetType靜態方法(http://stackoverflow.com/questions/7839691/gettype-靜態方法) – Zbigniew 2013-04-20 13:15:44

回答

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

是的,我想在此期間自己使用泛型。 – 2013-04-20 13:23:33

+2

如果您使用這樣的泛型,請考慮如果您有'ExtendedClass:CurrentClass'會發生什麼情況:'Method'將獲得'CurrentClass',而不是'ExtendedClass'。 – 2013-04-20 13:31:36

0

的方法不能static,如果你要調用它,而不傳遞一個類型。你可以這樣做:如果調用此

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

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

如果你還需要它是從一個static上下文訪問,您可以添加過載,即使是普通的過載,如僅從派生類,你可以使用「System.Diagnostics.StackTrace」像

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" 
    } 
} 
相關問題