I have two classes, first:
public class A
{
public delegate void Function();
public string name;
public Function function;
public A(string name, Function function)
{
this.name = name;
this.function = function;
}
}
And in second:
public class B
{
public delegate void Function();
List<A> ListA;
// somewhere in function
void F()
{
ListA[i].function();
}
// ---
public void AddA(string name, Function function)
{
ListA.Add(new A(name, function)); // error here
}
}
It throws these errors:
Error 2 Argument 2: cannot convert from 'App.B.Function' to 'App.A.Function'
Error 1 The best overloaded method match for 'App.A.A(string, App.A.Function)' has some invalid arguments
How to solve this?
You have declared
Functiondelegate twice, one inside class A and one inside B.So they’re two different types, one called
App.B.Functionand the other calledApp.A.Function.If you want to share this delegate with both the classes, just declare it once and out of the scope of the classes (i.e. in the assembly scope) e.g.:
However, in the
Systemnamespace exist a certain number of generic delegates that can be used to represent various functions. Have a look atSystem.Action<>andSystem.Func<>types.