LoginSignup
14
14

More than 5 years have passed since last update.

C# フィールドやprivateメソッドを無理やり使用する

Posted at

プロジェクトTestClassLib(クラスライブラリ)内にあるTestClassのフィールドおよびprivateメソッドを、プロジェクトConsoleApp(コンソールアプリケーション)から無理やり利用する方法

testClass.cs(プロジェクトTestClassLib内)

namespace TestClassLib
{

    public class TestClass
    {
        private double _field = 3.141592;

        private int PrivateMethod(int a, int b)
        {
            return a + b;
        }

    }
}
Program.cs(プロジェクトConsoleApp内)

using System;
using System.Reflection;
using TestClassLib;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            TestClass tc = new TestClass();
            Type type = tc.GetType();

            //// 以下privateフィールドの値を無理やり取得する
            // Typeからフィールドを探す。フィールド名とBindingFlagsを引数にする。
            FieldInfo field = type.GetField("_field", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance);
            double privateField = (double)(field.GetValue(tc));

            //// 以下privateメソッドを無理やり使用する方法
            // Typeからメソッドを探す。メソッド名とBindingFlagsを引数にする。
            MethodInfo method = type.GetMethod("PrivateMethod", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Instance);
            // インスタンスを作成する
            object instance = Activator.CreateInstance(type);
            // 探したメソッドを実行する。 呼ぶメソッドはint,intを引数にし、戻り値もintのため、intにcastしている
            int methodResult = (int)(method.Invoke(instance, new object[2] { 3, 4 }));
        }
    }
}

14
14
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
14
14