C# 7 ValueTuple compile error
我正在使用VS2017 RC,我的应用程序目标是NET Framework 4.6.1。
我有两个引用System.ValueTuple 4.3的程序集
我的项目服务我的项目.webapi
在myproject.services中,我有一个类具有这样的方法
1 2 3 4 5 | public async Task<(int fCount, int cCount, int aCount)> GetAllStatsAsync() { // Some code... return (fCount, cCount, aCount); } |
在myproject.webapi中,我有一个使用如下方法的控制器:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public async Task<HttpResponseMessage> GetInfoAsync() { // Some code... var stats = await _myClass.GetAllStatsAsync(); var vm = new ViewModel { FCount = stats.fCount, CCount = stats.cCount, ACount = stats.aCount }; return Request.CreateResponse(HttpStatusCode.OK, vm); } |
IntelliSense正在工作并解构元组,但是当我编译它时,它会在错误列表窗口中没有任何错误而失败。在输出窗口中,我有以下错误:
2>MyController.cs(83,31,83,40): error CS1061: 'ValueTuple' does not contain a definition for 'fCount' and no extension
method 'fCount' accepting a first argument of type 'ValueTuple' could be found (are you missing a using directive or an
assembly reference?) 2>MyController.cs(84,39,84,49): error CS1061:
'ValueTuple' does not contain a definition for 'cCount'
and no extension method 'cCount' accepting a first argument of type
'ValueTuple' could be found (are you missing a using
directive or an assembly reference?) 2>MyController.cs(85,35,85,40):
error CS1061: 'ValueTuple' does not contain a
definition for 'aCount' and no extension method 'aCount' accepting a
first argument of type 'ValueTuple' could be found (are
you missing a using directive or an assembly reference?)
我尝试添加demo和demo_实验构建标志,但仍然失败。
知道怎么回事吗?
编辑1:
这段代码可以工作,并且统计数据可以很好地解构。我可能碰到了一只虫子。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public async Task<HttpResponseMessage> GetInfoAsync() { // Some code... var stats = await _myClass.GetAllStatsAsync(); var tu = stats.ToTuple(); var vm = new ViewModel { FCount = tu.Item1, CCount = tu.Item2, ACount = tu.Item3 }; return Request.CreateResponse(HttpStatusCode.OK, vm); } |
编辑2:
在GitHub上打开的问题:https://github.com/dotnet/roslyn/issues/16200
如果有人落入同一个陷阱,要解决此问题,需要更新此包:Microsoft.NET.Compilers到2.0(需要显示预发布)
我认为这是因为你没有定义fcount、ccount和acount。试试这个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | public async Task<(int fCount, int cCount, int aCount)> GetAllStatsAsync() { // Some code... //fCount, cCount, aCount are not defined here, so you should define them var fCount = 0; var cCount= 0; var aCount = 0; return (fCount , cCount, aCount ); //Other ways: //return (fCount : 0, cCount: 0, aCount : 0); //return new (int fCount , int cCount, int aCount ) { fCount = 0, cCount = 0, aCount = 0 }; } public async Task<HttpResponseMessage> GetInfoAsync() { // Some code... var stats = await _myClass.GetAllStatsAsync(); var vm = new ViewModel { FCount = stats.fCount, CCount = stats.cCount, ACount = stats.aCount }; return Request.CreateResponse(HttpStatusCode.OK, vm); } |
用@swell建议编辑
看看这个帖子