gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-05 02:29:16 28 4
gpt4 key购买 nike

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

 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com