c# - C# 中输出参数的良好实践

我曾经是一名 C/C++ 程序员,但刚接触 C#。

我想从函数返回多个参数以及状态,所以我想将它们用作输出参数。这是一个例子。

bool SomeFunction(string inStr, out string outStr)
{
    if (someCondition)
    {
        outStr = AnotherFunction(inStr);
        return true;
    }
    return false;
}

我只想根据某些条件而不是总是根据某些条件设置 outStr 的值。但是,它无法编译,我必须使用如下值初始化 outStr。

bool SomeFunction(string inStr, out string outStr)
{
    outStr = string.Empty; // this makes it compile
    if (someCondition)
    {
        outStr = AnotherFunction(inStr);
        return true;
    }
    return false;
}

如果某些条件失败,我希望不初始化它。在那种情况下,我想在不初始化的情况下返回错误。我知道可以使用关键字 ref 而不是 out,而且我知道 ref 和 out 之间的区别。在这种用例中使用 ref 是一种好习惯吗?函数中输出参数的最佳实践是什么。提前致谢!

最佳答案

现在这里通常首选值元组或自定义结果类型。特别是,与 out 不同,此方法与 async 代码兼容。 out 也有一个普遍不被理解的名声。

例子:

(bool Success, string Message) SomeFunction(...)
{
    ...
    bool result = ...
    ...
    string msg = ...
    ...
    return (success, msg);
}

注意:如果 false 表示一个错误而不仅仅是一个信号:请考虑抛出异常;这通常(但不总是)更可取。

https://stackoverflow.com/questions/59702128/

相关文章:

django - 错误模块 'tablib.formats._xls' 没有属性 'title'

html - 容器中元素之间的空间

angular - 将 Angular 4 升级到 Angular 8

python - 从 BigQuery 获取数据需要很长时间

stripe-payments - 在 Stripe CLI 中使用 fixtures

c# - 如何在 ServiceStack 中返回不同的 Http Status Code

php - 如何在php中将一个元素添加到子数组中

python - 为什么 randn 并不总是均值为 0 且方差为 1?

swiftui - 如何修复无法在 Swift 中找到文件 json

xcode - SwiftUI:如何创建自定义 UIDatePicker?