I created a delegate and I want to use a delegate as a parameter in the method parameter list. I think I want to call a handler, as in the Main method, which works fine.
Question: How to pass a delegate to a method?
The code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public delegate void Del(string e);
Del handler = DelegateMethod;
public static void DelegateMethod(string message)
{
System.Console.WriteLine(message);
System.Console.ReadKey();
}
public void testDel(Del d) <--Write Here!!!
{
d.handler("33");
}
static void Main(string[] args)
{
Program p = new Program();
p.handler("Hello World"); <--Like this example here (these work)
p.handler("DisneyLand");
p.handler("Cattle Wars");
testDel(p.handler("Cattle Wars");
}
}
}
List of errors:
Error 1 The best overloaded method match for 'ConsoleApplication1.Program.testDel(ConsoleApplication1.Program.Del)' has some invalid arguments C:\Users\itpr13266\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs 36 12 ConsoleApplication1
Error 2 Argument 1: cannot convert from 'void' to 'ConsoleApplication1.Program.Del' C:\Users\itpr13266\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs 36 20 ConsoleApplication1
Error 3 ) expected C:\Users\itpr13266\AppData\Local\Temporary Projects\ConsoleApplication1\Program.cs 36 44 ConsoleApplication1
Work code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
public delegate void Del(string e);
Del handler = DelegateMethod;
public static void DelegateMethod(string message)
{
System.Console.WriteLine(message);
System.Console.ReadKey();
}
public void testDel(Del d)
{
d.Invoke("L");
}
static void Main(string[] args)
{
Program p = new Program();
p.handler("Hello World");
p.handler("DisneyLand");
p.handler("Cattle Wars");
p.testDel(p.handler);
}
}
}
user3376708
source
share