22

C#で呼び出し元のメソッドの完全な名前を見つけるにはどうすればよいですか? 私は解決策を見てきました:

C# で呼び出しメソッドを取得する方法

現在のメソッドを呼び出したメソッドを見つけるにはどうすればよいですか?

呼び出された関数から呼び出し関数名を取得

しかし、彼らは私にトップレベルしか与えません。例を考えてみましょう:

namespace Sandbox
{
    class Program
    {
        static void Main(string[] args)
        {
            test();
        }

        static void test()
        {
            var stackTrace = new StackTrace();
            var methodBase = stackTrace.GetFrame(1).GetMethod();
            Console.WriteLine(methodBase.Name);
        }
    }
}

これは単に「Main」を出力します。「Sandbox.Program.Main」を印刷するにはどうすればよいですか?

これは、私が取り組んでいる単純なログ フレームワーク用です。


Matziの回答に追加:

解決策は次のとおりです。

namespace Sandbox
{
    class Program
    {
        static void Main(string[] args)
        {
            test();
        }

        static void test()
        {
            var stackTrace = new StackTrace();
            var methodBase = stackTrace.GetFrame(1).GetMethod();
            var Class = methodBase.ReflectedType;
            var Namespace = Class.Namespace;         // Added finding the namespace
            Console.WriteLine(Namespace + "." + Class.Name + "." + methodBase.Name);
        }
    }
}

本来のように「Sandbox.Program.Main」を生成します。

4

5 に答える 5

33

これは、ここのようなものです。

MethodBase method = stackTrace.GetFrame(1).GetMethod();
string methodName = method.Name;
string className = method.ReflectedType.Name;

Console.WriteLine(className + "." + methodName);
于 2012-07-06T18:38:00.367 に答える
1

この方法を使用すると、フルネームを確実に取得できます

    public void HandleException(Exception ex, [CallerMemberName] string caller = "")
    {
        if (ex != null)
        {
            while (ex.InnerException != null)
                ex = ex.InnerException;

            foreach (var method in new StackTrace().GetFrames())
            {
                if (method.GetMethod().Name == caller)
                {
                    caller = $"{method.GetMethod().ReflectedType.Name}.{caller}";
                    break;
                }
            }

            Console.WriteLine($"Exception: {ex.Message} Caller: {caller}()");
        }
    }
于 2016-11-08T14:02:24.233 に答える
0

System.Reflection.MethodBaseメソッドではGetCurrentMethod、クラスなどを使用してコール スタックに関する完全な情報を見つけることができます。

于 2012-07-06T18:40:26.613 に答える