获取创建对象的类的名称

Vic*_*jee 1 .net c# reflection

我有两个课程如下:

第一:

class Class1
 {
     private void Method1()
      {
          var obj=new TestClass();
          obj.TestMethod1();
      }
 }
Run Code Online (Sandbox Code Playgroud)

第二个:

class TestClass
 {
     public void TestMethod1()
      {
           TestMethod2();
      }

      private void TestMethod2()
       {
           //get the calling class 
       }
 }
Run Code Online (Sandbox Code Playgroud)

当Class1.Method1调用TestClass.TestMethod1这反过来又来电TestClass.TestMethod2,我想的完全限定类名Class1内TestClass.TestMethod2.我看过这个链接,但我想我会得到TestClass.TestMethod1方法名和TestClass类名.我怎样才能获得调用类名称?

Mar*_*ell 7

没有好办法做到这一点.你可以访问堆栈帧(只看第二帧,而不是第一帧) - 但这是昂贵和脆弱的.您可以使用可选的caller-member-name属性(显式来自TestMethod1)来获取"Method1",但不能使用"Class1"部分.另一种选择是明确传入一个对象(或只是名称); 例如:

  private void Method1()
  {
      var obj=new TestClass();
      obj.TestMethod1(this);
  }
  public void TestMethod1(object caller=null,
             [CallerMemberName] string callerName=null)
  {
       TestMethod2(caller??this,callerName??"TestMethod1");
  }

  private void TestMethod2(object caller=null,
             [CallerMemberName] string callerName=null)
  {
      string callerName = ((caller??this).GetType().Name) + "." + callerName
      //get the calling class 
  }
Run Code Online (Sandbox Code Playgroud)

但我必须承认这很难看

或许更好的是首先要问你为什么需要这个.