Suppose there is a next class

class Example { public static void Main() { SayHello(); Console.ReadLine(); } public static void SayHello() => Console.WriteLine("Hello"); } 

How can another class be aware of calling the SayHello method without making changes to this? Perhaps reflection can achieve this? But the search for msdn did not give anything like

2 answers 2

I think that reflection cannot achieve this.

Reflection is not a panacea for all diseases.

No, of course you can call a method, and then with a reflection put the label in the class field, but by doing so you break the internal state.

I do not understand why you might need this ...

You can make a wrapper for the mediation class and, through it, jerk your class, and the mediator himself will make notes that the method has been called.

    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 
    • static method, as in the example, cannot be overridden - Grundy
    • @Grundy: The answer was not about static methods. - LLENN
    • one
      And in a question an example just with them - Grundy