gpt4 book ai didi

c# - .NET 4.7 返回元组和可为 null 的值

转载 作者:太空狗 更新时间:2023-10-29 20:09:25 25 4
gpt4 key购买 nike

好吧,假设我在 .NET 4.6 中有这个简单的程序:

using System;
using System.Threading.Tasks;

namespace ConsoleApp1
{
class Program
{
static async void Main()
{
var data = await Task.Run(() =>
{
try
{
return GetResults();
}
catch
{
return null;
}
});

Console.WriteLine(data);
}

private static Tuple<int,int> GetResults()
{
return new Tuple<int,int>(1,1);
}
}
}

工作正常。因此,在 .NET 4.7 中,我们有了新的元组值类型。因此,如果我将其转换为:

using System;
using System.Threading.Tasks;

namespace ConsoleApp1
{
class Program
{
static async void Main()
{
var data = await Task.Run(() =>
{
try
{
return GetResults();
}
catch
{
return null;
}
});

Console.WriteLine(data);
}

private static (int,int) GetResults()
{
return (1, 2);
}
}
}

太棒了!除了它不起作用。新的元组值类型不可为空,因此甚至无法编译。

有没有人找到一个很好的模式来处理这种情况,您想要传回一个值类型元组,但结果也可能为空?

最佳答案

通过添加可空类型运算符 ?,您可以使 GetResults() 函数的返回类型可为空:

private static (int,int)?  GetResults()
{
return (1, 2);
}

您的代码将无法编译,因为 Main() 函数中不允许使用 async。 (只需调用 Main() 中的另一个函数)


编辑:自从引入 C# 7.1(仅在最初发布此答案几个月后),允许使用 async Main 方法。

关于c# - .NET 4.7 返回元组和可为 null 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43946997/

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