调用类方法作为参数
c#
可以在 C# 上做这样的事情吗?我想要一个通用的 void 来从另一个类调用不同的方法。
public class custom{
public void A(){}
public void B(){}
}
void doSomething(List<custom> laux, method m ){
foreach(var aux in laux){
aux.m; //something like this
}
}
void main(){
doSomething(new List<custom>(),A);
doSomething(new List<custom>(),B);
}
回答
你可以通过委托做一些与此接近的事情Action:
void doSomething(List<custom> laux, Action<custom> m ){
foreach(var aux in laux){
m(aux);
}
}
void main(){
doSomething(new List<custom>(),c=> c.A());
doSomething(new List<custom>(),c=> c.B());
}