c# - 试图将从多个函数返回的 "similar looking"元组映射到一个变量

标签 c#

假设有一个包含这种形式代码的库:

 public class SomeLib
{
    public (bool WasOk, string Message) DoCheck(string fileName)
    {
        // do something here to check the file. 
        return (true, "all good");
    }

    public (bool WasOk, string Message) DoCheck(byte[] fileBytes)
    {
        // do something here to check the file as bytes 
        return (true, "all good");
    }
}

使用这个库的代码看起来像这样:

    int option = 1;

    SomeLib lib = new SomeLib();

    if (option == 0)
    {
        var res1 = lib.DoCheck("hello");
        MessageBox.Show(res1.WasOk + res1.Message);
    }
    else
    {
        var res2 = lib.DoCheck(new byte[] { });
        MessageBox.Show(res2.WasOk + res2.Message);
    }

我希望做的是将两次调用 DoCheck 的返回值存储到一个公共(public)变量中。例如:

    int option = 1;

    SomeLib lib = new SomeLib();

    var res; // doesn't compile, obviously

    if (option == 0)
    {
        res = lib.DoCheck("hello");                
    }
    else
    {
        res = lib.DoCheck(new byte[] { });
    }

    MessageBox.Show(res.WasOk + res.Message);  // act on the result in the same way for both branches. 

我希望这是有道理的。我正在尝试做的事情可能吗?假设库中的代码无法更改。

最佳答案

var res 无法编译,因为它没有任何类型信息。如果你正在做一个声明变量的语句,编译器必须能够从左侧或右侧以某种方式计算出类型:

StringBuilder sb = new StringBuilder(); //both sides, available from the dawn of time
var sb = new StringBuilder();           //for a long time
StringBuilder sb = new();               //more recently

如果没有右边那么左边必须有类型信息:

StringBuilder sb;

因此,对于您的情况,您需要将类型信息放在左侧。您甚至可以重命名成员(但您不必这样做)

(bool AllGood, string Note) res;

(bool WasOk, string Message) res;

(bool, string) res;  //access the bool in res.Item1, string in res.Item2

你可以用一个三元组来完成:

var res = (option == 0) ? lib.DoCheck(hello) : lib.DoCheck(new byte[] { });

你的两个方法都返回具有相同命名成员的元组,所以你的 res 将有 res.WasOkres.Message 所以它被编译为如果是这样:

(bool WasOk, string Message) res = ...

如果你的元组出来你的方法有不同的名字,它仍然会像这样编译:

(bool, string) res = ...

而且您仍然可以通过 Item1 和 Item2 访问数据


如果您正在执行这种三元方法,那么您也可以解构元组,这也允许您重命名:

var(allGood, note) = ... ? ... : ... ;

MessageBox.Show(note);

而不是你说 res.Whatever 的一个元组变量,这创建了两个变量,就像你这样做一样:

var res = ... ? ... : ... ;
var allGood = res.WasOk;
var note = res.Message;

有很多处理元组的选项..

关于c# - 试图将从多个函数返回的 "similar looking"元组映射到一个变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72268226/

相关文章:

c# - 如何使用 Gekofx 将参数从 C# 按值传递到 javascript 函数

c# - XAML 中的泛型

c# - 如何将 jquery 的 UI 自动完成与 ASP.NET 和外部数据源一起使用?

c# - 如何在Nest中创建快照?

c# - 如何阻止 SonarLint 抑制的警告不断重新出现在 VS 错误屏幕中

javascript - WebBrowser 中具有 Doctype 的不同 JavaScript 行为

c# - 使用 Azure 地理冗余 (RA-GRS) 表存储时,如何更新 ASP.NET Core 中的 TableServiceClient 以指向辅助区域?

紧凑框架上的 C# Double.TryParse 等效项

c# - 使用 C# MongoDB 驱动程序,如何序列化对象引用的集合?

c# - 单元测试用例调试时如何读取Web.Config文件?