我在 C# 3.5 中有两个相同的方法,除了一个函数调用, 在下面的代码片段中,请参阅 clientController.GetClientUsername 与 clientController.GetClientGraphicalUsername
private static bool TryGetLogonUserIdByUsername(IGetClientUsername clientController, string sClientId, out int? logonUserId)
{
string username;
if (clientController.GetClientUsername(sClientId, out username))
{
// ... snip common code ...
}
return false;
}
private static bool TryGetLogonUserIdByGraphicalUsername(IGetClientUsername clientController, string sClientId, out int? logonUserId)
{
string username;
if (clientController.GetClientGraphicalUsername(sClientId, out username))
{
// ... snip common code ...
}
return false;
}
有没有一种方法(委托(delegate),lamda 的?)我可以传递我想调用的 clientController 上的哪个方法?
谢谢!
最佳答案
虽然您可以将委托(delegate)作为参数传递,但我建议采用不同的方法。将涉及公共(public)代码的if
语句体封装在另一个函数中,并在两个函数中调用该函数。
Visual Studio 在上下文菜单中具有“重构 ->
提取方法”功能。您可以只填写其中一个主体,选择主体并使用该功能自动从中提取方法。
关于c# - 在 C# 3.5 中,如何将调用对象的方法作为参数传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1026623/