Skip to main content
 首页 » 编程设计

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

2024年02月24日29hnrainll

我有以下方法:

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 的代码可能永远不会在给定的执行路径中运行。