怪奇物语

怪奇物语

首页 新随笔 联系 管理

C#获取当前的类名,函数,命名空间

dotnet 命令行创建项目

dotnet new console -n <项目名称>
dotnet new console -n LogOut

Program.cs

using LogOut.Utils;
var res = Calculator.Add(20, 30);
Console.WriteLine(res);

Calculate.cs

关键代码:

MethodBase currentMethod = MethodBase.GetCurrentMethod()!;
// 获取当前执行的方法的命名空间
string namespaceName = currentMethod.DeclaringType!.Namespace!;
// 获取当前执行的方法的类名
string className = currentMethod.DeclaringType.Name;
// 获取当前执行的方法的方法名
string methodName = currentMethod.Name;

// 打印当前执行的方法的信息
Console.WriteLine("当前执行的方法的信息:");
Console.WriteLine("命名空间:{0}", namespaceName);
Console.WriteLine("类名:{0}", className);
Console.WriteLine("方法名:{0}", methodName);

LogOut.Utils.Calculator.cs


using System.Reflection;

namespace LogOut.Utils
{
    public class Calculator
    {

        // 定义一个名为 Add 的函数,接受两个 double 类型的参数,返回它们的和
        public static double Add(double a, double b)
        {

            MethodBase currentMethod = MethodBase.GetCurrentMethod()!;
            // 获取当前执行的方法的命名空间
            string namespaceName = currentMethod.DeclaringType!.Namespace!;
            // 获取当前执行的方法的类名
            string className = currentMethod.DeclaringType.Name;
            // 获取当前执行的方法的方法名
            string methodName = currentMethod.Name;

            // 打印当前执行的方法的信息
            Console.WriteLine("当前执行的方法的信息:");
            Console.WriteLine("命名空间:{0}", namespaceName);
            Console.WriteLine("类名:{0}", className);
            Console.WriteLine("方法名:{0}", methodName);
            return a + b;
        }
    }
}

posted on 2023-09-21 11:28  超级无敌美少男战士  阅读(1047)  评论(0)    收藏  举报