Home >Backend Development >C++ >How Can I Get the Name of the Currently Executing Method in C#?

How Can I Get the Name of the Currently Executing Method in C#?

Linda Hamilton
Linda HamiltonOriginal
2025-01-11 09:43:44175browse

How Can I Get the Name of the Currently Executing Method in C#?

Get the current method name from code

To determine the name of the currently executing method, use the System.Reflection.MethodBase.GetCurrentMethod().Name attribute. This property provides access to the current method name, allowing you to identify the method in your code.

Usage:

Inside a method, call the System.Reflection.MethodBase.GetCurrentMethod().Name attribute to retrieve the name of the current method:

<code class="language-csharp">// 获取当前方法的名称
string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;</code>

Example:

Consider the following code:

<code class="language-csharp">class MyClass
{
    public void MyMethod()
    {
        // 获取当前方法的名称
        string methodName = System.Reflection.MethodBase.GetCurrentMethod().Name;
        Console.WriteLine("当前方法名称: {0}", methodName);
    }
}</code>

When the MyMethod method is called, it executes the code within the method. During execution, it calls the System.Reflection.MethodBase.GetCurrentMethod().Name attribute to get the name of the current method, which is "MyMethod". Then print the results to the console.

The above is the detailed content of How Can I Get the Name of the Currently Executing Method in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn