If your class is not private, and can be inherited from it, then we do so, inherit from this class, override the real SayHello method by specifying the new keyword in the SayHello method of the heir class to the compiler. Let's write a simple delegate (you can use Action ) and event , as well as a method that will call the delegate (read more about c # callbacks) . Next, let's subscribe to the created event, and send the message to the console that will come from the class of the heir (In this example, Trace used in test classes) .
Work Result: https://ideone.com/PiWlQU
public class Example { public void SayHello() => Console.WriteLine("Hello"); } public class DeviredExample : Example { public delegate void MethodCall(object sender, string message); public event MethodCall CallMethod; protected virtual void OnCallMethod(string message, Action callback) { callback?.Invoke(); CallMethod?.Invoke(this, message); } public new void SayHello() { OnCallMethod("Say hello called", () => base.SayHello()); } }
[TestMethod] public void Test() { DeviredExample d = new DeviredExample(); int i = 0; d.CallMethod += (sender, message) => { Trace.WriteLine(message); i = 1; }; d.SayHello(); if (i != 0) { Assert.IsTrue(true); return; } Assert.Fail(); }
Test result:
Tests (1 test) [0:00.989] Success yami.ui.tests (1 test) [0:00.989] Success yami.ui.tests.Services (1 test) [0:00.989] Success SettingsModelTest (1 test) [0:00.989] Success Test [0:00.989] Success Трассировка отладки: Hello Say hello called