ダメプログラマーのチラシウラ

メタプログラミング

最終更新:

boatassist

- view
だれでも歓迎! 編集
※下記のサンプルデータを対象にしたものです
※using System.Reflection;

  private フィールドに値を入れる
       /// <summary>
       /// private フィールドに値を突っ込むサンプル
       /// </summary>
       private void SetPrivateValue()
       {
           Generater gene = new Generater();
           Type type = typeof(Generater);
           FieldInfo info = type.GetField("pValue", BindingFlags.SetField | BindingFlags.NonPublic | BindingFlags.Instance);
           info.SetValue(gene, "できた!!!");
           Console.WriteLine(gene.GetValue());
       }

  戻り値無しのprivate メソッドの実行サンプル
       /// <summary>
       /// 戻り値無しのprivate メソッドの実行サンプル
       /// </summary>
       private void ExecPrivateMethod()
       {
           Generater gene = new Generater();
           Type type = typeof(Generater);
           MethodInfo method = type.GetMethod("GetData", BindingFlags.NonPublic | BindingFlags.Instance, null
                   , new Type[] { typeof(string), typeof(DateTime), typeof(MethodBase) }, null);
           MethodBase methodBase = null;
           method.Invoke(gene, new object[] { "できるかな?", DateTime.Now, methodBase });
       }

  戻り値有りのprivate メソッドの実行サンプル
       /// <summary>
       /// 戻り値有りのprivate メソッドの実行サンプル
       /// </summary>
       private void ExexPrivateMethodReturn()
       {
           Generater gene = new Generater();
           Type type = typeof(Generater);
           MethodInfo method = type.GetMethod("GetData", BindingFlags.NonPublic | BindingFlags.Instance, null
                               , new Type[] { typeof(string), typeof(object) }, null);
           object obj = method.Invoke(gene, new object[] { "戻り値希望!", null });
           if (obj == null) Console.WriteLine("失敗");
           Console.WriteLine(((EventMessage)obj).time.ToString());
       }




サンプルデータクラス
   public class EventMessage
   {
       public string val = "data";
       public string Daata = "data";
       public DateTime time = DateTime.Now;
   }
   public class Generater
   {
       private int Count;
       private string pValue;
       Generater s_Instance;
       public Generater()
       {
           s_Instance = this;
       }
       public string GetValue()
       {
           return pValue;
       }
       public void GetData(string val)
       {
           Console.WriteLine(val);
       }
       public void GetData(string val, DateTime date)
       {
           Console.WriteLine(val);
       }
       private EventMessage GetData(string val, object obj)
       {
           EventMessage e = new EventMessage();
           return e;
       }
       private void GetData(string val, DateTime date, MethodBase method)
       {
           Console.WriteLine(val);
       }
   }

タグ:

+ タグ編集
  • タグ:

このサイトはreCAPTCHAによって保護されており、Googleの プライバシーポリシー利用規約 が適用されます。

目安箱バナー