【问题标题】:How to know caller class C# [duplicate]如何知道调用者类 C# [重复]
【发布时间】:2019-08-10 17:51:21
【问题描述】:

我有以下类结构。 A 类是从 B 类和 C 类的构造函数中调用的。

Class A
{
    A()
}

Class B
{
    B()
    {
        A();
    }
}

Class C
{
    C()
    {
        A();
    }
}

有什么方法可以让我知道对 A() 的调用是来自 B() 还是 C()? 我不想在构造函数中传递任何对象。

【问题讨论】:

  • 可能会有所帮助:stackoverflow.com/a/1375429/6299857
  • 不是直接的。让 A 的行为依赖于使用它的类可能是不好的做法——下次你想从一个完全不同的类中使用 A 时,你会感到惊讶。最好通过参数将所有输入传递给构造函数,这样 A 的工作原理就很明显,并且可以很容易地被其他类使用(可重用性!)。

标签: c# class


【解决方案1】:

您可以使用CallerMemberNameAttribute 获取来电者姓名。请查看here 中的以下示例。希望这会有所帮助。

public void DoProcessing()
{
    TraceMessage("Something happened.");
}

public void TraceMessage(string message,
        [System.Runtime.CompilerServices.CallerMemberName] string memberName = "",
        [System.Runtime.CompilerServices.CallerFilePath] string sourceFilePath = "",
        [System.Runtime.CompilerServices.CallerLineNumber] int sourceLineNumber = 0)
{
    System.Diagnostics.Trace.WriteLine("message: " + message);
    System.Diagnostics.Trace.WriteLine("member name: " + memberName);
    System.Diagnostics.Trace.WriteLine("source file path: " + sourceFilePath);
    System.Diagnostics.Trace.WriteLine("source line number: " + sourceLineNumber);
}

// Sample Output:
//  message: Something happened.
//  member name: DoProcessing
//  source file path: c:\Visual Studio Projects\CallerInfoCS\CallerInfoCS\Form1.cs
//  source line number: 31

【讨论】:

    【解决方案2】:

    这对我有用

    var mth = new StackTrace().GetFrame(1).GetMethod();
    var cls = mth.ReflectedType.Name;
    

    【讨论】:

      【解决方案3】:

      您需要 CallerMemberNameAttribute 或 CallerFilePathAttribute。 更多细节请参考微软文档 https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/caller-information

      public class FirstClass
      {
           public string Run([CallerMemberName] string memberName = "", [CallerFilePath] string sourceFilePath = "")
          {
              return $"CallerMemberName is {memberName}. Calling from {sourceFilePath}";
          }
      }
      
      public class SecondClass
      {
          public string CallFirstClass()
          {
              var firstClass = new FirstClass();
              return firstClass.Run();
          }
      }
      

      CallFirstClass() 中的输出是这样的

      CallerMemberName is CallFirstClass. Calling from D:\Development\WpfApp1\WpfApp1\SecondClass.cs
      

      【讨论】:

        猜你喜欢
        • 2020-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-10
        • 1970-01-01
        • 2017-05-03
        • 1970-01-01
        • 2010-11-12
        相关资源
        最近更新 更多