【问题标题】:C# get a list of functions that call a certain function [duplicate]C#获取调用某个函数的函数列表[重复]
【发布时间】:2017-05-31 23:22:33
【问题描述】:

这有点与这个问题相切:

Retrieving the calling method name from within a method

public Main()
{
     PopularMethod();
}

public ButtonClick(object sender, EventArgs e)
{
     PopularMethod();
}

public Button2Click(object sender, EventArgs e)
{
     PopularMethod();
}

public void PopularMethod()
{
     //Get calling method name
}

是否可以使用反射来获取调用其主体中“PopularMethod”函数的函数列表? 即:[Main, ButtonClick, Button2Click]

更新:C# reflection and finding all references 是我要找的!哇!谢谢大家

【问题讨论】:

  • 当然 - Visual Studio 中的静态分析工具和其他第 3 方工具可以做到这一点。不过,框架中没有内置任何内容。
  • @D Stanley 我想这些工具会解析实际代码并可以通过这种方式定位声明/用法。我想知道您为什么要以编程方式执行此操作?
  • 解决方案应该类似于这个one

标签: c# reflection


【解决方案1】:

您可以使用一个属性让运行时服务为您获取此信息:

public void PopularMethod([System.Runtime.CompilerServices.CallerMemberName] string memberName = "")
{

}

在这里阅读更多: https://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.callermembernameattribute(v=vs.110).aspx

【讨论】:

  • 感谢胡安的回复,但这不是我想要的。这需要调用 PopularMethod。我更希望只使用 C# 反射而不调用任何方法来获得编程调用层次结构。
  • 我现在明白了。那么看看这个:stackoverflow.com/questions/31861762/…
【解决方案2】:

看看System.Diagnostics,那里有StackTrace 类可能会有所帮助。

StackTrace st = new StackTrace(true);
for(int i =0; i< st.FrameCount; i++ )
{
    // Note that high up the call stack, there is only
    // one stack frame.
    StackFrame sf = st.GetFrame(i);
    Console.WriteLine();
    Console.WriteLine("High up the call stack, Method: {0}",
        sf.GetMethod());

    Console.WriteLine("High up the call stack, Line Number: {0}",
        sf.GetFileLineNumber());
}

【讨论】:

  • 你可以用它来找到所有调用PopularFunction的被调用函数。这不会找到对未被调用的事物的引用,因此不确定这是否可以提供每个引用的列表。
猜你喜欢
  • 1970-01-01
  • 2014-09-11
  • 2010-11-21
  • 1970-01-01
  • 2013-06-27
  • 2012-12-29
  • 2021-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多