Home > Software design >  Is this possible at the c# event?
Is this possible at the c# event?

Time:12-26

using static main.main2;

namespace main;
class MainClass
{
    public delegate void dele();
    public static event dele? eve;

    private static void Main()
    {
        eve  = a;
        if (eve != null) { eve(); }
    }
}
static class main2
{
    public static void a()
    {
        Console.WriteLine("A");
    }
}

I made an example to specifically ask the question. If method a() is deleted from the above example, an error occurs in eve = a; this part. I know why there is an error. Is there a way to prevent errors without method a()? Is there a way to add a to eve only when method a() exists?

Thank you for reading it. I'd appreciate your help.

CodePudding user response:

Yes, You could use reflection to check whether method a is defined or not and based on it you can call eve = a;

var methodInfo = typeof(main2).GetMethod("a", BindingFlags.Static | BindingFlags.Public);
if (methodInfo != null)
{
    eve  = main2.a;
}
  •  Tags:  
  • c#
  • Related