pardeike / Harmony

A library for patching, replacing and decorating .NET and Mono methods during runtime
https://www.patreon.com/pardeike
MIT License
5.15k stars 485 forks source link

How to patch method of base class? #596

Closed MaxLevs closed 6 months ago

MaxLevs commented 6 months ago

Base class has method, child inherited it. How can i patch this method throught child

using HarmonyLib;

namespace TestHarmony.VirtualMethodPatching
{
    class Program
    {
        static void Main(string[] args)
        {
            Harmony harmony = new(nameof(TestHarmony));
            harmony.PatchAll(typeof(Program).Assembly);

            Subclass instance = new();
            instance.OnDestroy();
            Console.ReadKey();
        }
    }

    public class Subclass : BaseClass
    {
        // Has OnDestroy() that calls BaseClass.OnDestroy() as default behaviour
    }

    public class BaseClass
    {
        public virtual void OnDestroy()
        {
            Console.WriteLine("BaseClass");
        }
    }

    // It's trying to patch OnDestroy method of Subclass which is BaseClass.OnDestroy
    [HarmonyPatch(typeof(Subclass))]
    [HarmonyPatch("OnDestroy")]
    static class LocationPatch
    {
        public static void Prefix()
        {
            Console.WriteLine("Prefix");
        }
    }
}
pardeike commented 6 months ago

Support and questions regarding usage are answered on the official discord.