C# lambda 内容在被调用之前不会发生,对吗?另外,代码清理

标签 c# refactoring lambda dry

我有以下方法:

protected static void updateExistingSection(XmlDocument doc,
    XmlNode rootNode, string sectionTag, CreateSection createSection,
    Func<XmlNode[]> createChildNodes, Action<XmlNode> firstSection)
{
    IEnumerable<XmlNode> sections =
        getChildNodesByName(rootNode, sectionTag);
    if (sections.Count() < 1)
    {
        rootNode.AppendChild(createSection(doc, createChildNodes()));
        return;
    }
    removeSubsequentNodes(sections, rootNode, firstSection);
}

private static void updateExistingCredentialsSection(XmlDocument doc,
    XmlNode rootNode, string newUser, string newPassword, string newHost)
{
    updateExistingSection(doc, rootNode, CREDENTIALS_SECTION_TAG,
        createCredentialsSection,
        () => new[] {
            createNode(USER_TAG, doc, newUser),
            createNode(PASSWORD_TAG, doc, newPassword),
            createNode(HOST_TAG, doc, newHost)
        },
        credentialsNode =>
        {
            updateExistingLeafNode(USER_TAG, doc, credentialsNode, newUser);
            updateExistingLeafNode(PASSWORD_TAG, doc, credentialsNode,
                newPassword);
            updateExistingLeafNode(HOST_TAG, doc, credentialsNode, newHost);
        });
}

我的问题涉及 updateExistingCredentialsSection 中传递给 updateExistingSection 的第五个参数,() => new[] { createNode(USER_TAG, doc, newUser), ... 一个。据我了解,那些 createNode 调用不会发生,除非在 updateExistingSection 中调用了 lambda 表达式,对吧?同样,对于 updateExistingLeafNode 调用,最后一个参数给 updateExistingSection

另外,从设计的角度来看,这两种方法看起来是否荒谬?您是否看到一种方法可以使任一方法更小,或者需要更少的参数?我一直在尝试 DRY 事情,这就是导致首先编写 updateExistingSection 的原因,因为我有几种方法执行相同的功能。

最佳答案

正确。将 lambda 视为方法。您可以在任何地方定义它们(法律允许),但其中的代码只有在明确调用后才会运行。

事实上,如果您将它们传递给的函数中存在分支逻辑,则某些 lambda 的代码可能永远不会在给定的执行路径中运行。

关于C# lambda 内容在被调用之前不会发生,对吗?另外,代码清理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2998805/

相关文章:

c# - 使用表达式 lambda 进行异常处理

java - 如何在 Beanshell 中使用或转义 java 8 Lambda 表达式

c# - 我应该给这个 cookie 什么域?

c# - 在 RichTextBox 中设置插入符/光标位置 - WPF

c# - 如何替换部分连接字符串?

delphi - 如何检测接口(interface)和实现uses子句中无用的Delphi单元?

python - 在 Python 中创建一个带有匿名函数的字典

c# - 使用 ODP.NET 的第一次查询总是很慢

代码目录结构-库设计

language-agnostic - 如何识别短代码块可以重构为更干净的东西?