Dav*_*ing 5 c# refactoring delegates .net-3.5
我在C#3.5中有两个相同的bar一个函数调用方法,在下面的代码片段中,请参阅clientController.GetClientUsername vs 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;
}
Run Code Online (Sandbox Code Playgroud)
有没有办法(委托,lamda的?)我可以传递给我想调用的clientController上的哪个方法?
谢谢!
虽然您可以将委托作为参数传递,但我建议使用不同的路径.封装if
涉及另一个函数中的公共代码的语句的主体,并在两个函数中调用该代码.
Visual Studio ->
在上下文菜单中具有"重构提取方法"功能.您只需填写其中一个实体,选择实体并使用该功能自动提取其中的方法.
当然.只需像这样定义一个委托:
public delegate bool GetUsername(string clientID, out string username);
Run Code Online (Sandbox Code Playgroud)
然后将其传递给您的函数并调用它:
private static bool TryGetLogonUserId(IGetClientUsername clientController, string sClientId, out int? logonUserId, GetUsername func)
{
string username;
if (func.Invoke(sClientId, out username))
{
// ... snip common code ...
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
要使用委托调用该函数,您将执行以下操作:
TryGetLogonUserId(/* first params... */, clientController.GetClientUsername);
Run Code Online (Sandbox Code Playgroud)