C# リフレクションまとめ4 (メンバを実行する)
ConstructorInfoを実行して、型のインスタンスを生成する
using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace ReflectionTest { class ClassA { public ClassA() { Console.WriteLine("Constructor is called."); } public void Method() { Console.WriteLine("Method is called."); } private Int32 i = 0; public Int32 Property { get { return i; } set { i = value; } } } class Program { static void Main(string[] args) { Type t = typeof(ClassA); ConstructorInfo ci = t.GetConstructor(new Type[0]); ClassA ca = (ClassA)ci.Invoke(new Object[0]); ca.Method(); } } }
MethodInfoを実行して、型のメソッドを呼び出す
using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace ReflectionTest { class ClassA { public ClassA() { Console.WriteLine("Constructor is called."); } public void Method() { Console.WriteLine("Method is called."); } private Int32 i = 0; public Int32 Property { get { return i; } set { i = value; } } } class Program { static void Main(string[] args) { Type t = typeof(ClassA); Object o = Activator.CreateInstance(t); MethodInfo mi = t.GetMethod("Method"); mi.Invoke(o, null); } } }
PropertyInfoを実行して、getアクセサ、setアクセサを呼び出す
using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace ReflectionTest { class ClassA { public ClassA() { Console.WriteLine("Constructor is called."); } public void Method() { Console.WriteLine("Method is called."); } private Int32 i = 0; public Int32 Property { get { return i; } set { i = value; } } } class Program { static void Main(string[] args) { Type t = typeof(ClassA); Object o = Activator.CreateInstance(t); PropertyInfo pi = t.GetProperty("Property"); //Set MethodInfo setMethod = pi.GetSetMethod(); setMethod.Invoke(o, new Object[1] { 100 }); Console.WriteLine(((ClassA)o).Property); //Get MethodInfo getMethod = pi.GetGetMethod(); Int32 ret = (Int32)getMethod.Invoke(o, null); Console.WriteLine(ret); } } }
publicなフィールドの値を設定、取得する
FieldInfoのGetValue、SetValueを使う。
using System; using System.Collections.Generic; using System.Text; using System.Reflection; namespace ReflectionTest { class ClassA { public ClassA() { Console.WriteLine("Constructor is called."); } public void Method() { Console.WriteLine("Method is called."); } private Int32 i = 0; public Int32 Property { get { return i; } set { i = value; } } public String s = null; } class Program { static void Main(string[] args) { Type t = typeof(ClassA); Object o = Activator.CreateInstance(t); FieldInfo fi = t.GetField("s"); fi.SetValue(o, "Reflection"); ClassA ca = (ClassA)o; Console.WriteLine(ca.s); String s = (String)fi.GetValue(o); Console.WriteLine(s); } } }