如果失败,"out" 参数应该是什么?

What should an "out" parameter be in case of failure?

我读过这个相关问题:What should the out value be set to with an unsuccessfull TryXX() method?

然而,该问题涉及基本类型,例如整数等

我正在实现一个类似的TryXXX,那个问题的答案说当方法不成功时out的默认值应该是null。但是,我的方法中的 out 类型是不可为 null 的值类型。

以我的代码为例:

    public bool TryParseFileLine(string fileLine, out FileResult result)
    {
        if(!string.IsNullOrWhiteSpace(fileLine))
        {
            result = null;
            return false;
        }
        // Logic here for if the string wasn't empty etc.
    }

    public struct FileResult
    {
        public bool IsValid;
        public string Value;
    }

result = null 行无法编译,因为 Cannot convert null to 'FileResult' because it is a non-nullable value type.

所以在我的情况下,当方法失败时 result 的值应该是多少?理想情况下,我希望它为空,因为这对我来说最有意义。

编辑:在这里使用 Nullable<FileResult> 是个好主意吗?例如:

        public bool TryParseFileLine(string fileLine, out Nullable<FileResult> result)
    {
        if(!string.IsNullOrWhiteSpace(fileLine))
        {
            result = null;
            return false;
        }
        // Logic here for if the string wasn't empty etc.
        result = new FileResult();
    }

what should the value of result be when the method fails?

您可以简单地使用 default(FileStruct)

这将为您提供具有默认值的 FileStruct。但是你不会关心它,因为你只在 return false 时才这样做,因此调用者不会使用这个值。

根据经验,要么使用 default(FileStruct)(并确保该值具有某种意义 - 它等同于值类型的 new FileStruct()),或者更好的是, 完全抓取 out 参数 和 return 一个可为 null 的 FileStruct? 值。

public FileResult? TryParseFileLine(string fileLine)
{
    if (string.IsNullOrWhiteSpace(fileLine))
        return null;

    ...
}

bool TrySomething(out Result result) 模式早于语言中的可空结构,恕我直言,不应将其用于新代码,因为它会给调用者带来不便(因为大多数情况下都需要声明一个附加变量时间)。
使用可为空的结构作为 return 值对调用者来说要好得多,并且不需要您在代码中使用 return 无意义的值。