我之前也曾提出过类似的问题(并已回答),但是当我将一种方法传递给另一种方法时,我意识到我仍然有一个谜题。我的问题是当将方法作为参数传递时,如何包含参数?我在下面提供了一个示例。
任何帮助,不胜感激。
非常感谢,
服务电话
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
方法:
private string RunMethod(Func<int, string> methodToRun, int id)
{
var result = methodToRun(id);
..
}
id
如果需要,您也始终可以使之具有可选输入:
int id= 10
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句