在C#7中使用Var模式 [英] Usage of Var Pattern in C# 7

查看:62
本文介绍了在C#7中使用Var模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在新的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模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆