我有两个班,第一个:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
第二个:
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
}
}
Run Code Online (Sandbox Code Playgroud)
它抛出这些错误:
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
Run Code Online (Sandbox Code Playgroud)
怎么解决这个?
你已经Function两次声明了委托,一个在A类内部,一个在B内.
所以它们是两种不同的类型,一种叫App.B.Function,另一种叫App.A.Function.
如果要与这两个类共享此委托,只需将其声明一次并超出类的范围(即在程序集范围内),例如:
public delegate void Function();
public class A
{
public string name;
...
}
public class B
{
List<A> ListA;
...
}
Run Code Online (Sandbox Code Playgroud)
但是,在System命名空间中存在一定数量的通用委托,可用于表示各种功能.看看System.Action<>和System.Func<>类型.