サンプル集  >  C#  >  メソッド名の取得
メソッド名の取得
2017/11/20

メソッド名を取得し表示してみます。

◆環境
OS Windows 7 Professional Service Pack 1 (64bit)
C# 01018-587-4054026-70893

以下の手順を行います。

  1. [ファイル]-[新規作成]-[プロジェクト]を選択します。
  2. 「プロジェクトの種類」欄で[Visual C#]を選択し、[コンソール アプリケーション]を選択します。
    「プロジェクト名」は「MethodNameTest」にします。

メソッド名の取得にはMethodBase.GetCurrentMethod()を使います。

Program.cs
 1: 
 2: 
 3: 
 4: 
 5: 
 6: 
 7: 
 8: 
 9: 
10: 
11: 
12: 
13: 
14: 
15: 
16: 
17: 
18: 
19: 
20: 
21: 
22: 
23: 
24: 
25: 
26: 
27: 
28: 
29: 
30: 
31: 
32: 
33: 
34: 
35: 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace MethodNameTest
{
    class Program
    {
        static void Main( string[] args )
        {
            Console.WriteLine( MethodBase.GetCurrentMethod() );
            Console.WriteLine( MethodBase.GetCurrentMethod().Name );
            func1();

            Console.Read();
        }

        static void func1()
        {
            Console.WriteLine( MethodBase.GetCurrentMethod() );
            Console.WriteLine( MethodBase.GetCurrentMethod().Name );
            func2( 1 );
        }

        static void func2( int i )
        {
            MethodBase mb = MethodBase.GetCurrentMethod();
            Console.WriteLine( mb );
            Console.WriteLine( mb.Name );
            Console.WriteLine( mb.DeclaringType );
        }
    }
}

実行してみます。

Void Main(System.String[])
Main
Void func1()
func1
Void func2(Int32)
func2
MethodNameTest.Program

メソッド名だけを取得したい場合、Nameプロパティを使うとよさそうです。

DeclaringTypeプロパティを使うと、このメソッドが宣言されたクラスを取得できます。

▲ PageTop  ■ Home


Copyright (C) 2017 ymlib.com