当参数为 true 时指示结果不为 null 的属性?

Jon*_*ood 6 c# c#-8.0 nullable-reference-types .net-5 c#-9.0

我有类似以下方法的东西。

public Node? GetLastNode(bool createNewIfEmpty = false)
{
    // Return last node if any
    if (Nodes.Count > 0)
        return Nodes[Nodes.Count - 1];

    // Return a new appended node, if requested
    if (createNewIfEmpty)
    {
        Nodes.Add(new Node());
        return Nodes[0];
    }

    // Otherwise, return null
    return null;
}
Run Code Online (Sandbox Code Playgroud)

在可空引用类型打开的情况下,是否有任何属性(或其他方式)来指定只要参数为 ,此方法就永远不会返回createNewIfEmptynull true

Xer*_*lio 0

我不确定是否NotNullIfNotNull可以为您解决这个问题,但另一种方法是将方法分成两部分,除非您有硬要求从参数中控制它:

public Node? GetLastNode()
{
    // Return last node if any. Otherwise, return null
    return Nodes.Count > 0
        ? Nodes[^1]
        : null;
}

public Node GetOrCreateLastNode()
{
    // Add new node if the list is empty
    if (Nodes.Count == 0)
        Nodes.Add(new Node());

    // Return the last node
    return Nodes[^1];
}
Run Code Online (Sandbox Code Playgroud)