我安装了Visual Studio 15 Preview 3并尝试使用新的元组功能
static void Main(string[] args)
{
var x = DoSomething();
Console.WriteLine(x.x);
}
static (int x, int y) DoSomething()
{
return (1, 2);
}
Run Code Online (Sandbox Code Playgroud)
当我编译时,我收到错误:
未定义或导入预定义类型'System.ValueTuple'2'
根据博客文章,这个功能默认情况下应该"打开".
我做错了什么?
在C#7中我们可以使用
if (x is null) return;
Run Code Online (Sandbox Code Playgroud)
代替
if (x == null) return;
Run Code Online (Sandbox Code Playgroud)
使用新方法(前一个例子)比旧语法有什么好处吗?
语义学有什么不同?
只是品味问题?如果没有,何时使用一个或另一个.
参考.
我正在研究C#7.0中的新实现,我觉得有趣的是他们已经实现了本地函数,但我无法想象一个局部函数比lambda表达式更受欢迎的场景,两者之间有什么区别.
我知道lambdas是anonymous
函数,而局部函数却没有,但我无法弄清楚一个真实世界的场景,其中局部函数优于lambda表达式
任何例子都将非常感激.谢谢.
Visual Studio 2017(15.x)支持C#7,但Visual Studio 2015(14.x)呢?
我怎样才能使用C#7?
我反编译了一些C#7库并看到了使用的ValueTuple
泛型.是什么ValueTuples
以及为什么不Tuple
呢?
我知道这可能听起来很奇怪,但我甚至不知道如何在互联网上搜索这种语法,我也不确定究竟是什么意思.
所以我看了一些MoreLINQ代码然后我注意到了这个方法
public static IEnumerable<TSource> DistinctBy<TSource, TKey>(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector, IEqualityComparer<TKey> comparer)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (keySelector == null) throw new ArgumentNullException(nameof(keySelector));
return _(); IEnumerable<TSource> _()
{
var knownKeys = new HashSet<TKey>(comparer);
foreach (var element in source)
{
if (knownKeys.Add(keySelector(element)))
yield return element;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这个奇怪的回报声明是什么?return _();
?
C#6.0中的新功能允许在TryParse方法中声明变量.我有一些代码:
string s = "Hello";
if (int.TryParse(s, out var result))
{
}
Run Code Online (Sandbox Code Playgroud)
我做错了什么?PS:在项目设置中设置C#6.0和.NET framework 4.6.
给出以下代码:
string someString = null;
switch (someString)
{
case string s:
Console.WriteLine("string s");
break;
case var o:
Console.WriteLine("var o");
break;
default:
Console.WriteLine("default");
break;
}
Run Code Online (Sandbox Code Playgroud)
为什么switch语句匹配case var o
?
因为(有效地)评估为false case string s
,s == null
所以我的理解不匹配(null as string) != null
.VS Code上的IntelliSense告诉我这o
也是一个string
.有什么想法吗?
类似于:C#7切换案例,带有空检查
我已经安装了一周前发布的Visual Studio 2017社区,我开始探索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);
}
Run Code Online (Sandbox Code Playgroud)
编译器生成错误:
错误CS8137无法定义使用元组的类或成员,因为无法找到编译器所需类型"System.Runtime.CompilerServices.TupleElementNamesAttribute".你错过了参考吗?
我试着用这个名字在框架中找到一个引用,但没有运气!
如果我们需要额外的东西来使用C#7.0功能,那么我们需要为每个项目做到这一点非常奇怪吗?
我知道可以使用using关键字在C#中定义别名.
例如
using ResponseKey = System.ValueTuple<System.Guid, string, string>;
Run Code Online (Sandbox Code Playgroud)
但是,是否可以使用值元组的新语法定义一个?
using ResponseKey = (Guid venueId, string contentId, string answer);
Run Code Online (Sandbox Code Playgroud)
此语法似乎不起作用.应该是?