【问题标题】:Get current class at runtime in a static method?在运行时以静态方法获取当前类?
【发布时间】:2013-04-13 19:10:48
【问题描述】:

如何在抽象类的静态方法中获取当前类的类型(不是名称字符串,而是类型本身)?

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?

但是,我想从静态方法中获取这些信息。

【问题讨论】:

标签: c# reflection static abstract


【解决方案1】:
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
    }

}

您只需将类型作为泛型类型参数传递给基类,即可从静态方法访问派生类型。

【讨论】:

  • 是的,与此同时,我自己也想使用泛型。
  • 如果你使用这样的泛型,考虑一下如果你得到ExtendedClass : CurrentClass会发生什么:Method 将得到CurrentClass,而不是ExtendedClass
【解决方案2】:

我认为您必须像其他建议一样传递它或创建一个堆栈框架,我相信如果您将整个堆栈跟踪放在一起,尽管它可能很昂贵。

http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx

【讨论】:

    【解决方案3】:

    如果您要在不传入类型的情况下调用该方法,则该方法不能是static。你可以这样做:

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

    如果您还需要从 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());
        }
    }
    

    【讨论】:

      【解决方案4】:

      如果您仅从派生类调用此静态方法,您可以使用类似“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"
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-08
        • 1970-01-01
        • 1970-01-01
        • 2010-10-10
        • 2023-02-23
        • 2018-09-26
        • 2010-11-07
        • 1970-01-01
        相关资源
        最近更新 更多