以前我发布过类似的问题(和答案),但是我意识到在将方法传递给另一个方法时仍然缺少一部分难题。我的问题是当一个方法作为参数传递时,如何包含参数?我在下面包含了一个例子。将方法作为参数传递给另一个方法,但参数为
任何帮助非常感谢。
非常感谢,
服务电话
private readonly MemberRepo _memberRepo;
public SomeService()
{
_memberRepo = new MemberRepo();
}
public string GetMembers(int id)
{
// This works, i.e. the RunMethod internally calls the Get method on the repo class - problem: how can I pass the id into the repo Get method?
var result = RunMethod(_memberRepo.Get);
...
return stuff;
}
private string RunMethod(Func<int, string> methodToRun)
{
var id = 10; // this is a hack - how can I pass this in?
var result = methodToRun(id);
..
}
库
public class MemberRepo
{
public string Get(int id)
{
return "Member from repository";
}
}
更新
private string RunMethod(Func<int, string> methodToRun)
{
if(id.Equals(1))
{
// Do something
//
var result = methodToRun(id);
..
}
哦对!傻我,我一直与RunMethod战斗(_memberRepo.Get(id)) – Jamie