Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 检索调用方法&;来自委托的元数据_C#_.net_Reflection - Fatal编程技术网

C# 检索调用方法&;来自委托的元数据

C# 检索调用方法&;来自委托的元数据,c#,.net,reflection,C#,.net,Reflection,是否有可能从给定方法内部检索有关调用它的方法的任何信息 public void MethodOne() { for (int nCount = 0; nCount < 10; nCount++) MethodTwo(); } public void MethodTwo() { // Can I retrieve here information about the call to MethodOne which originated this call? } public v

是否有可能从给定方法内部检索有关调用它的方法的任何信息

public void MethodOne()
{
   for (int nCount = 0; nCount < 10; nCount++) MethodTwo();
}
public void MethodTwo()
{
   // Can I retrieve here information about the call to MethodOne which originated this call?
}
public void MethodOne()
{
对于(int-nCount=0;nCount<10;nCount++)MethodTwo();
}
公共空间方法二()
{
//我可以在这里检索有关发起此调用的MethodOne调用的信息吗?
}

例如,在这种情况下,我希望能够在运行时知道,对
MethodTwo
的一组给定的十个调用是由给定线程中对
MethodOne
的调用发起的。。。这可能吗?

不容易,但如果您检查当前堆栈跟踪,这是可能的:

using System.Diagnostics;

// ...

StackTrace t = new StackTrace();
如果您需要根据调用方的身份使代码的行为有所不同,那么应该在方法中添加一个额外的参数,调用方可以使用该参数来标识自己

如果您使用此信息调试应用程序,那么您可能希望使用一个探查器,它可以告诉您此类信息,而无需修改代码。

这太可怕了:

string caller0 = new StackFrame(1).GetMethod().Name; // MethodOne
string caller1 = new StackFrame(2).GetMethod().Name; // whatever called MethodOne

(这也不是免费的;任何这样的滥用都要付出性能代价)

您只想计算直拨电话吗?如果Method1调用Foo,那么Foo调用Bar,Bar调用MethodTwo呢?您可能不喜欢它,但是调用
Method2(“MethodOne”)
(或者其他表达原点的方式)在这里可以说是一种合理的机制……还值得注意的是,除了性能成本,这也可能是不可靠的:抖动可能决定内联这些方法中的任何一个,但不适用于委托调用。