2013-04-20 42 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" 
    } 
} 
相关问题