假设有一个带有此表单代码的库:

 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的两次调用返回的值存储到一个公共变量中.例如.:

    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;

处理元组有很多 Select ..

Csharp相关问答推荐

[0-n]范围内有多少个Integer在其小数表示中至少包含一个9?

List T.AddRange在传递ConcurrentDictionary作为参数时引发ArgumentExcellent

为什么xslWriter不总是按照xslWriterSet中指定的格式格式化该文档?

无法从具有一对多关系的C#类中使用Swagger创建记录

如何使用XmlSerializer反序列化字符串数组?

Blazor Foreach仅渲染最后一种 colored颜色

模型绑定RazorPage表单

ASP.NET核心REST API返回一个非常大的数字

Blazor WebApp:原始异常:AADSTS700025:客户端是公共的,因此既不应显示客户端,也不应显示客户端

C#-VS2022:全局使用和保存时的代码清理

.NET SDK包中的官方C#编译器在哪里?

Linux Docker上的.NET6在某个时间抛出后,在加密操作期间发生System.Security.Cryptography.CryptographicException:错误

将内置的OrderedEumable&Quot;类设置为内部类有什么好处?

在两个已具有一对多关系的表之间添加另一个一对多关系

如何在mediatr命令中访问HttpContext而不安装弃用的nuget包

使用可空引用类型时C#接口实现错误

当我手动停止和关闭系统并打开时,Windows服务未启动

使用C#代码和SQL SERVER中的相同证书签名会产生不同的结果

.NET文档对继承的困惑

实体框架允许您具有筛选的属性吗?