首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >c# harmony示例未按预期打印注入日志

c# harmony示例未按预期打印注入日志
EN

Stack Overflow用户
提问于 2019-12-31 11:34:26
回答 1查看 1.3K关注 0票数 2

C# harmony文档:https://github.com/pardeike/Harmony/wiki/Prioritiy-annotations我的问题是不能成功运行C# harmony示例

在类和方法打了补丁之后,postfix注解没有像预期的那样打印注入日志,我没有看到“注入日志”被打印出来。

下面是c#代码示例。有人能帮我找到你可以粘贴到https://dotnetfiddle.net/中进行调试的问题吗?

代码语言:javascript
运行
复制
using System;
using System.Collections.Generic;
using System.Reflection;
using Harmony;

public class Program
{
    public static void Main()
    {
        var harmony = HarmonyInstance.Create("net.example.plugin");
        harmony.PatchAll(Assembly.GetExecutingAssembly());
        Program p = new Program();
        p.Bar();
    }

    [HarmonyPostfix]
    [HarmonyPatch(typeof(Program), "Bar")]
    public static void Postfix_Bar(){ 
        Console.WriteLine("postfix Bar log");  // this never gets printed as expected. 
    }

    [HarmonyPostfix]
    [HarmonyPatch(typeof(Program), "Foo")]
    public static void Postfix_Foo(ref string res){  //however, this gets error res could not be found.  https://github.com/pardeike/Harmony/wiki/Prioritiy-annotations
        Console.WriteLine("postfix Foo log");
        res = "new value";
    }

    public void Bar() {
        Console.WriteLine("Hello World !!! ");
    }

    static string Foo()
    {
        return "secret";
    }
}
EN

回答 1

Stack Overflow用户

发布于 2020-01-28 19:33:12

主要问题是PatchAll()查找至少包含[HarmonyPatch]注释的类。您的补丁位于Program类中,该类没有该注释。这是示例中的主要问题。

解决方案:要么像这样注释你的Program类:

代码语言:javascript
运行
复制
[HarmonyPatch]
public class Program
{
}

或者创建一个具有该注释的新类。

我能看到的第二个问题是Postfix_Foo(ref string res)使用res,它没有遵循文档中记录的命名补丁参数的标准。它既可以是原始方法具有的参数的名称(它没有参数),也可以引用结果,这需要将其命名为__result

关于优先级注释的注释也放错了地方,因为它们只适用于同一原始方法的多个补丁。

最后,在打补丁之后调用Bar(),这意味着永远不会调用Foo --不确定这是否是有意的。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/59539270

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档