Unable to return Tuple from a method using Visual Studio 2017 and C# 7.0

送分小仙女□ 提交于 2019-12-17 17:59:30

问题


I've installed Visual Studio 2017 Community that was released a week ago, and I started exploring the new features of C# 7.

So I created a simple method that returns two values:

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

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

Compiler is generating an error:

Error CS8137 Cannot define a class or member that utilizes tuples because the compiler required type 'System.Runtime.CompilerServices.TupleElementNamesAttribute' cannot be found. Are you missing a reference?

I tried finding a reference in the framework with this name, but with no luck !

If we need additional stuff to use C# 7.0 features, then it is very weird that we need to do that for every project ?!


回答1:


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)

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!




回答2:


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.




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/40826704/unable-to-return-tuple-from-a-method-using-visual-studio-2017-and-c-sharp-7-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!