オブジェクトの情報を一覧する.cs
[C#]
System.Reflection名前空間のクラスを使う。
System.ObjectのメソッドであるGetType()を使うと、System.Typeクラスのインスタンスを取得できる。
このTypeクラスには、GetMembers()、GetMethods()、GetProperties()、GetFields()などのオブジェクトの情報を返すメソッドがある。
これらのメソッドの返り値は、System.Reflection名前空間で定義されているクラスに相当する。
それぞれ、System.Reflection.MemberInfo、MethodInfo、PropertyInfo、FieldInfoクラスになる。
以下は、DirectoryInfoオブジェクトのメンバを一覧する例。
using System; using System.IO; using System.Reflection; ...... DirectoryInfo di = new DirectoryInfo(args[0]); foreach (MemberInfo mi in di.GetType().GetMembers()) { Console.WriteLine("Name: {0}, Type: {1}", mi.Name, mi.MemberType); }
実行中のアセンブリを取得するには、Assembly.GetExecutingAssembly()を使えばよい。
using System; using System.Reflection; class AssemblyTest { public static void Main(string[] args) { Assembly asm = Assembly.GetExecutingAssembly(); Console.WriteLine(asm.FullName); Console.WriteLine(asm.Location); foreach (Type t in asm.GetTypes()) { Console.WriteLine(t.Name); foreach (MemberInfo mi in t.GetMembers()) { Console.WriteLine("\tName: {0}, Type: {1}", mi.Name, mi.MemberType); } } } }