无法从使用 Visual Studio 2017和 C # 7.0的方法返回 Tuple

我已经安装了一周前发布的 Visual Studio 2017 Community,并开始探索 C # 7的新特性。

因此,我创建了一个返回两个值的简单方法:

public class Program
{
public static void Main(string[] args)
{
(int sum, int count) a = ReturnTwoValues();
}


static (int sum, int count) ReturnTwoValues() => (1, 1);
}

编译器正在生成一个错误:

错误 CS8137无法定义使用元组的类或成员 因为编译器要求 “ System.Runtime.CompilerServices.TupleElementNamesAttribute”不能是 找到了。你是不是少了一个推荐信?

我试图在框架中找到这个名称的引用,但是没有找到!

如果我们需要额外的东西来使用 C # 7.0特性,那么对于每个项目我们都需要这样做是非常奇怪的吗!

31203 次浏览

I Just ran through this page on Roslyn which describes the following steps to get this working:

  1. Start a C# project
  2. Add a reference to the System.ValueTuple package from NuGet (pre-release)

enter image description here

Following those steps, it is now working. But it is really very weird that we need to do that for every single project that we start! Hope this is fixed when we reach the Official release!

I started getting this error after I installed .Net 4.7 Framework, and changed my project to target .Net 4.7

ValueTuple is now included with .Net 4.7, so you don't have to reference the ValueTuple manually.

All I had to do to correct the compile error was remove the reference to System.ValueTuple from my project's references.

I also came accross this issue as I upgraded from .NET 4.6.2 to .NET 4.7.2. Unfortunately, I was not able to remove the package reference to System.ValueTuple because another NuGet package I use depends on it.

Finally I was able to locate the root cause: There was a .NET 4.6.2 version of mscorlib.dll lying around in the project folder (output of a publish operation) and MSBuild decided to reference this assembly instead of the official .NET 4.7.2 reference assembly located in C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.7.2.

Due to the fact that System.ValueTuple was introduced in .NET 4.7, MSBuild failed the compilation because it could not find the type in the reference assembly of .NET 4.6.2.

I got this error too after updating to .NET 4.7.2 and was able to fix it by re-installing nuget packages using:

Update-Package -Reinstall