如何找到称为当前方法的方法?
登录C#时,如何学习称为当前方法的方法的名称?我对 System.Reflection.Methodbase.getCurrentMethod()
了解全部了解,但是我想在堆栈跟踪中走一步。我已经考虑过解析堆栈跟踪,但是我希望找到一种更清洁的方法,例如 assembly.getCallingAssembly()
,但用于方法。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(17)
尝试一下:
单线:
Try this:
one-liner:
在C#5中,您可以使用 caller信息:
您还可以获取
[CallerFilePath]
和[CallerlineNumber]
。In C# 5, you can get that information using caller info:
You can also get the
[CallerFilePath]
and[CallerLineNumber]
.您可以使用呼叫者信息和可选参数:
此测试说明了这一点:
虽然stacktrace的工作原理很快,并且在大多数情况下,呼叫者信息的速度仍然更快。在1000次迭代的样本中,我将其计入了40倍的速度。
You can use Caller Information and optional parameters:
This test illustrates this:
While the StackTrace works quite fast above and would not be a performance issue in most cases the Caller Information is much faster still. In a sample of 1000 iterations, I clocked it as 40 times faster.
与速度比较的快速回顾是重要的部分。
档案/2013/07/25/c.net-little-tilter-getting-getting-caller-information.aspx
在compile time
使用堆栈确定呼叫者
两种方法的比较
A quick recap of the 2 approaches with speed comparison being the important part.
http://geekswithblogs.net/BlackRabbitCoder/archive/2013/07/25/c.net-little-wonders-getting-caller-information.aspx
Determining the caller at compile-time
Determining the caller using the stack
Comparison of the 2 approaches
我们可以通过仅实例化我们实际需要的框架而不是整个堆栈来改进阿萨德先生的代码(当前接受的答案):
这可能会更好,尽管很可能仍然必须使用完整的堆栈创建该单一帧。此外,它仍然具有与Alex Lyman指出的相同的警告(优化器/本机代码可能会损坏结果)。最后,您可能需要检查以确保
新的StackFrame(1)
或.getFrame(1)
否返回null
,as这种可能性似乎不太可能。请参阅此相关问题:
您可以使用反射来找到当前执行方法的名称?
We can improve on Mr Assad's code (the current accepted answer) just a little bit by instantiating only the frame we actually need rather than the entire stack:
This might perform a little better, though in all likelihood it still has to use the full stack to create that single frame. Also, it still has the same caveats that Alex Lyman pointed out (optimizer/native code might corrupt the results). Finally, you might want to check to be sure that
new StackFrame(1)
or.GetFrame(1)
don't returnnull
, as unlikely as that possibility might seem.See this related question:
Can you use reflection to find the name of the currently executing method?
通常,您可以使用
system.diarostics.diarostics.diarostics.stacktrace.stacktrace
类要获得
system.diagnostics.stackframe
,然后使用
getMethod()
获得system.reflection.methodbase
对象。但是,有一些警告对这种方法(注意:我只是在扩展答案 Firas Assad提供的答案)。
In general, you can use the
System.Diagnostics.StackTrace
class to get aSystem.Diagnostics.StackFrame
, and then use theGetMethod()
method to get aSystem.Reflection.MethodBase
object. However, there are some caveats to this approach:(NOTE: I am just expanding on the answer provided by Firas Assad.)
在.NET 4.5开始时,您可以使用“ noreferrer”>来电者信息属性:
- 称为函数的成员。
 
该设施也存在于“ .NET Core”和“ .NET标准”中。
参考
As of .NET 4.5 you can use Caller Information Attributes:
CallerFilePath
- The source file that called the function;CallerLineNumber
- Line of code that called the function;CallerMemberName
- Member that called the function.This facility is also present in ".NET Core" and ".NET Standard".
References
CallerFilePathAttribute
ClassCallerLineNumberAttribute
ClassCallerMemberNameAttribute
Class显然,这是一个较晚的答案,但是如果您可以使用.NET 4.5或更新的话,我有一个更好的选择:
这将打印当前日期和时间,然后是“ namespace.classname.methodname”,然后以“:text”结尾。 br>
样本输出:
样本使用:
Obviously this is a late answer, but I have a better option if you can use .NET 4.5 or newer:
This will print the current Date and Time, followed by "Namespace.ClassName.MethodName" and ending with ": text".
Sample output:
Sample use:
请注意,由于优化,这样做在发行代码中是不可靠的。此外,以沙盒模式运行应用程序(网络共享)不允许您完全抓住堆栈框架。
考虑“ noreferrer”> tockent-opent-opiented编程(aop),例如 postsharp ,它没有从代码中调用,而是修改代码,从而知道始终在哪里。
Note that doing so will be unreliable in release code, due to optimization. Additionally, running the application in sandbox mode (network share) won't allow you to grab the stack frame at all.
Consider aspect-oriented programming (AOP), like PostSharp, which instead of being called from your code, modifies your code, and thus knows where it is at all times.
也许您正在寻找这样的东西:
Maybe you are looking for something like this:
一个很棒的课程在这里: http://www.csharp411.com/c-get-get-呼叫方法/
A fantastic class is here: http://www.csharp411.com/c-get-calling-method/
要获得方法名称和班级名称,请尝试以下操作:
For getting Method Name and Class Name try this:
我使用的另一种方法是将参数添加到所讨论的方法中。例如,代替
void foo()
,使用void foo(字符串上下文)
。然后传递一些指示调用上下文的唯一字符串。如果您只需要呼叫者/上下文进行开发,则可以在运输前删除
param
。Another approach I have used is to add a parameter to the method in question. For example, instead of
void Foo()
, usevoid Foo(string context)
. Then pass in some unique string that indicates the calling context.If you only need the caller/context for development, you can remove the
param
before shipping.额外的信息给firas assaad答案。
我已经使用
新的stackframe(1).getMethod()。名称;
in .net core 2.1带有依赖项注入,并且我将调用方法作为“ start”。我尝试了
[System.Runtime.compilerServices.callermembername]字符串callername =“”
它给了我正确的呼叫方法
Extra information to Firas Assaad answer.
I have used
new StackFrame(1).GetMethod().Name;
in .net core 2.1 with dependency injection and I am getting calling method as 'Start'.I tried with
[System.Runtime.CompilerServices.CallerMemberName] string callerName = ""
and it gives me correct calling method
我们还可以使用lambda的目的来找到呼叫者。
假设您有一种定义的方法:
您想找到它的呼叫者。
1 。更改方法签名,以便我们具有类型动作的参数(func也将起作用):
2 。 lambda名称不是随机生成的。该规则似乎是:> < callermethodname> __ x
callermethodname被以前的函数替换,而x是索引。
3 。当我们调用Methoda时,必须通过呼叫者方法生成操作/弹性参数。
示例:
4 。在Methoda内部,我们可以调用上面定义的辅助函数,并找到呼叫者方法的方法。
例子:
We can also use lambda's in order to find the caller.
Suppose you have a method defined by you:
and you want to find it's caller.
1. Change the method signature so we have a parameter of type Action (Func will also work):
2. Lambda names are not generated randomly. The rule seems to be: > <CallerMethodName>__X
where CallerMethodName is replaced by the previous function and X is an index.
3. When we call MethodA the Action/Func parameter has to be generated by the caller method.
Example:
4. Inside MethodA we can now call the helper function defined above and find the MethodInfo of the caller method.
Example:
这是对 Camilo Terevinto的解决方案的略有改进
This is a slight improvement to Camilo Terevinto's solution because the calling convention is bit cleaner