c# - 在 C# 3.5 中,如何将调用对象的方法作为参数传递

标签 c# .net-3.5 delegates refactoring

我在 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/

相关文章:

c# - 使用动态字段名称使用 LINQ 查询实体

c# - 我拔下客户端工作站的插头,长时间运行的数据库进程会发生什么情况?

c# - Winforms 多线程 : Is creating a new delegate each time when invoking a method on the UI thread needed?

c# - 禁用 MaskedTextBox 声音

c# - WPF : Assigning to RichTextBox. 文档极慢(7 分钟!)

带有对 C++ 回调的字符串引用的 C# 委托(delegate)

c# - 需要 && 在一起不确定数量的 Func<TEntity, bool>

c# - 无法发送电子邮件 :( - The remote certificate is invalid according to the validation procedure

c# - 需要 CSS 方面的帮助

c# - 'yield return' 比 "old school"返回慢吗?