Kel*_*lly 7 c# tuples .net-4.7
好吧,我想在.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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
工作良好.因此,使用.NET 4.7,我们有了新的Tuple值类型.所以,如果我转换它,它变成:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
大!除了它不起作用.新的元组值类型不可为空,因此甚至无法编译.
任何人都找到一个很好的模式来处理这种情况,你想要传递一个值类型元组,但结果也可能是null?
Adr*_*ian 11
通过添加可空类型运算符,?您可以使GetResults()函数的返回类型为nullable:
private static (int,int)? GetResults()
{
return (1, 2);
}
Run Code Online (Sandbox Code Playgroud)
您的代码无法编译,因为函数中async不允许这样做Main().(只需调用另一个函数Main())
编辑:自从引入C#7.1(此答案最初发布后几个月),async Main允许使用方法.