うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【C#】Reflection 処理まとめ

メモがてらまとめる

子クラスかどうか

type.IsSubclassOf(baseType)

親のクラス

type.BaseClass

インナークラスの取得

// クラス名を指定して取得
type.GetNestedType("ClassName");

// 全インナークラスを取得
type.GetNestedTypes();

継承クラスを全検索

var types = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(a => a.GetTypes())
    .Where(t => !t.IsAbstract && t.IsSubclassOf(baseType))
    .ToArray();

インスタンス生成

var typeInstance = Activator.CreateInstance(type);

すべての Type の中から検索

AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(a => a.GetTypes())
    .Where(t => t.Name == "Hoge")

メソッド実行

var methodInfo = type.GetMethod("Method", BindingFlags.NonPublic | BindingFlags.Instance);
methodInfo.Invoke(object, new object[0]);

static なメソッドを実行

type.InvokeMember("Method", BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, null, new object[]{});

プロパティ取得

var propertyInfo = type.GetProperty("Property", BindingFlags.NonPublic);
propertyInfo.GetValue(object);

static なプロパティ取得

type.GetProperty("Property", BindingFlags.Static | BindingFlags.NonPublic)
    .GetValue();

ジェネリックメソッドの実行

var methodInfo = type.GetMethod("GenericMethod");
var genericMethod = methodInfo.MakeGenericMethod(genericType);
genericMethod.Invoke();

メソッドが override されているか

private static bool IsOverrideMethod(Type type, string methodName)
{
    var method = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.NonPublic);
    if (method == null)
        return false;
    return method.DeclaringType != method.GetBaseDefinition().DeclaringType;
}