C#での反射操作によるプライベートフィールドとプライベートメソッド

2786 ワード

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleApplication14
{
    class Program
    {
        static void Main(string[] args)
        {
            test t = new test();          
            try
            {
                AccessHelp.WritePrivateFiled(t, "_Hidden",
                    new object[] { "Hello World!" });
                Console.WriteLine(AccessHelp.ReadPrivateField(t, "_Hidden")
                    .ToString());
                Console.WriteLine(AccessHelp.ExecutePrivateMethod(t, "Hello",
                    new object[] { "Quist" }));
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.ReadKey();
        }
    }

    class test
    {
        private string _Hidden = null;
        public string Hidden
        {
            get
            {
                return _Hidden;
            }
        }

        private string Hello(string name)
        {
            return "Welcom! " + name;
        }
    }

    class AccessHelp
    {
        public static object ReadPrivateField(object instance, string name)
        {
            object result = null;
            try
            {
                Type t = instance.GetType();
                result = t.InvokeMember(name, BindingFlags.Instance | 
                    BindingFlags.NonPublic | BindingFlags.GetField, null, 
                    instance, null);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

        public static void WritePrivateFiled(object instance, string name, 
            object[] parameters)
        {
            try
            {
                Type t = instance.GetType();
                t.InvokeMember(name, BindingFlags.Instance |
                    BindingFlags.NonPublic | BindingFlags.SetField, null, 
                    instance, parameters);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public static object ExecutePrivateMethod(object instance, string name,
            object[] parameters)
        {
            object result = null;
            try
            {
                Type t = instance.GetType();
                result = t.InvokeMember(name, BindingFlags.Instance | 
                    BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, 
                    instance, parameters);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }
    }
}