C # method pointer as in C ++

In C ++ I was able to create a pointer to my method without knowing which instance it would be called on, but in C # I cannot do that - I need an instance to create a delegate.

This is what I am looking for:

Here is the code from MSDN

using System;
using System.Windows.Forms;

public class Name
{
   private string instanceName;

   public Name(string name)
   {
      this.instanceName = name;
   }

   public void DisplayToConsole()
   {
      Console.WriteLine(this.instanceName);
   }

   public void DisplayToWindow()
   {
      MessageBox.Show(this.instanceName);
   }
}

public class testTestDelegate
{
   public static void Main()
   {
      Name testName = new Name("Koani");
      Action showMethod = testName.DisplayToWindow;
      showMethod();
   }
}

      

But I want to do this:

public class testTestDelegate
{
    public static void Main()
    {
        Name testName = new Name("Koani");
        Action showMethod = Name.DisplayToWindow;
        testName.showMethod();
    }
}

      

+3


source to share


1 answer


You can create a delegate that takes your instance as a parameter:



Name testName = new Name("Koani");
Action<Name> showMethod = name => name.DisplayToWindow();
showMethod(testName);

      

+2


source







All Articles