代码之家  ›  专栏  ›  技术社区  ›  Sarah Vessels

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

  •  1
  • Sarah Vessels  · 技术社区  · 15 年前

    我有以下方法:

    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 , the () => new[] { createNode(USER_TAG, doc, newUser), ... } 一个。这是我的理解 createNode 除非在中调用lambda表达式,否则不会发生调用 更新现有节 对吧?同样适用于 updateExistingLeafNode 调用最后一个给定的参数 更新现有节 .

    另外,从设计的角度来看,这两种方法看起来都很荒谬吗?您是否看到了一种方法,我可以使方法变小,或者需要更少的参数?我一直想把东西弄干,这就是导致写作的原因。 更新现有节 首先,因为我有几个方法做相同的功能。

    1 回复  |  直到 15 年前
        1
  •  4
  •   Andrew Anderson    15 年前

    对的。把羊羔当作方法。您可以在任何地方定义它们(合法允许),但是它们中的代码只有在显式调用之后才能运行。

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