有没有办法对这个 return 值进行空注释(根据参数不为空)或者我是否需要重新设计?

Is there a way to null-annotate this return value (not null depending on arguments) or do I need to redesign?

此 API 定义早于可空性注释。有没有办法正确注释它,或者我是否需要重新设计 API 表面?

    public static IEnumerable<DirectoryEntry> GetDirectoryContents(string path,
        NonExtantDirectoryBehavior nonExtantDirectoryBehavior = NonExtantDirectoryBehavior.Throw,
        FollowSymbolicLinks followSymbolicLinks = FollowSymbolicLinks.Never)

nonExtantDirectoryBehavior 在调用者中永远是常量;如果参数的值为 ReturnNull.

GetDirectoryContents 只能 return null

我必须实际放置属性而不是使用 ?,但这是一个次要的细节。

GetDirectoryContents can only return null if the argument's value is ReturnNull.

System.Diagnostics.CodeAnalysis.MaybeNullWhenAttribute 是最接近该行为的,但它需要一个布尔参数。

如果您愿意修改方法签名以使该参数成为布尔值或使用单独的命名方法(例如 TryGetDirectoryContents),您可能会得到这种行为。否则,您可以只注意 return 值通常可以为 null,或者保持原样。