一:背景

1. 讲故事

本来想研究一下 IL编织反向补丁的相关harmony知识,看了下其实这些东西对 .NET高级调试 没什么帮助,所以本篇就来说一些比较实用的反射工具包吧。

二:反射工具包

1. AccessTools

AccessTools这个工具包用来简化反射操作,你如果看过 harmony 的底层代码,就会发现无处不在 AccessTools,比如 HarmonyPatch 的第20个重载方法。

//
    // Summary:
    //     An annotation that specifies a method, property or constructor to patch
    //
    // Parameters:
    //   typeName:
    //     The full name of the declaring class/type
    //
    //   methodName:
    //     The name of the method, property or constructor to patch
    //
    //   methodType:
    //     The HarmonyLib.MethodType
    public HarmonyPatch(string typeName, string methodName, MethodType methodType = MethodType.Normal)
    {
        info.declaringType = AccessTools.TypeByName(typeName);
        info.methodName = methodName;
        info.methodType = methodType;
    }

现在的好消息是你也可以直接使用 AccessTools,使用方式和 HarmonyPatch的构造函数注入方式几乎一摸一样, 为了方便演示,我们还是用 Thread 来跟大家聊一聊,我用大模型生成了一批例子。参考如下:

static void Main(string[] args)
        {
            var thread = new Thread(() => { });
            thread.Start();

            //1. 反射出 Thread.Start 方法。
            var original1 = AccessTools.Method(typeof(Thread), "Start", new Type[] { });