我已经在新的C#7中看到了var模式的示例
I've seen this example of var pattern in the new C# 7
if (o is var x) Console.WriteLine($"it's a var pattern with the type {x?.GetType()?.Name}");只是使用有什么不同:
var x = o; Console.WriteLine($"it's a var pattern with the type {x?.GetType()?.Name}");当此模式是有用的解决方案时。
And when this pattern is an useful solution.
推荐答案在该示例中没有实际区别。不幸的是,如此之多的网站都使用了—甚至语言参考。
There's no practical difference in that example. It's unfortunate that so many sites use that—even the language reference.
如果需要布尔表达式中的临时变量,则使用 x的主要原因是var y 模式。例如:
The main reason you would use the x is var y pattern if you need a temporary variable within a Boolean expression. For example:
allLists.Where(list => list.Count() is var count && count >= min && count <= max)通过创建临时变量 count 我们可以多次使用它,而无需每次调用 Count()的性能代价。
By creating temporary variable count we can use it multiple times without the performance cost of calling Count() each time.
在该示例中,我们可以使用 is int count 来代替— var 只是样式选择。但是,在两种情况下需要 var :对于匿名类型,或者如果您想允许为null。后者是因为 null 与任何类型都不匹配。
In that example we could have used is int count instead—the var is just a stylistic choice. However, there are two cases where var is needed: for anonymous types or if you want to allow nulls. The latter is because null doesn't match any type.
专门用于 if ,但是,您可以做同样的事情: if(list.Count()是var count&& count> = min& & count< =最大值)。但这显然很愚蠢。普遍的共识似乎是, if 并没有什么用。但是这种语言不会阻止您,因为从该特定的表达方式声明中禁止这种特定的表达形式会使该语言变得复杂。
Specifically for if, though, you could do the same thing: if (list.Count() is var count && count >= min && count <= max). But that's clearly silly. The general consensus seems to be that there's no good use for it in if. But the language won't prevent you, because banning this particular expression form from that specific expression-taking statement would complicate the language.
更多推荐
在C#7中使用Var模式
发布评论