为什么不允许使用'var'的复合定义? [英] Why are compound definitions using 'var' not allowed?

查看:108
本文介绍了为什么不允许使用'var'的复合定义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我真的认为这会起作用(在方法内):

Well, I really thought that this would work (inside a method):

var x, y = 1;

var x = 1, y = 2;

但它没有,它不会编译 - 化合物定义中不允许使用var。

But it does not, it would not compile - "var is not allowed in a compound definition".

我想这是一个平常的权衡。这不是一个非常常用的功能,因此没有实现,但我们可以肯定,可能会在将来的版本中...

I guess the reason for this is an usual trade-off. This is not a very used feature and thus not implemented, but we could yes and may be might in a future release...

推荐答案

好吧,如果你给它一个清单类型:

Well, if you give it a manifest type:

int x, y = 1;

这声明了两个int变量,并初始化其中一个变量。但是局部变量类型推断需要初始化器来推断类型。所以你已经死了。

This declares two int variables, and initializes one of them. But local variable type inference requires an initializer to infer a type. So you're dead out of the gate.

但是,假设您打算为两者提供初始化程序。当两个初始化程序具有相同类型时,显而易见该做什么。所以让我们变得更难。假设你说:

But, suppose you meant to provide an initializer for both. It's "obvious" what to do when both initializers have the same type. So let's make it harder. Suppose you said:

var x = 1, y = 2.0;

这是什么意思?这是否将 x 声明为 int y ?或者它是否尝试找到某种类型,可以是x和y的类型?无论我们决定哪一方,有些人会认为它应该以另一种方式运作,这将是根本上令人困惑的。

What is this supposed to mean? Does this declare x as int and y as float? Or does it try to find some type that can be the type of both x and y? Whichever we decided, some people would think it should work the other way, and it would be fundamentally confusing.

并且,为了什么好处?与潜在的语义混淆相比,说出你的意思的增量语法成本是微不足道的。这就是为什么我们将这种情况排除在本地人的类型推断范围之外。

And, for what benefit? The incremental syntactic cost of saying what you mean is trivial compared to the potential semantic confusion. And that's why we excluded this from the scope of type inference for locals.

然后,你可能会说,好吧,只有当它们属于同一类型时才能使它工作。我们可以做到这一点,但是现在你可以使用推理的时间边界,以及何时不是更复杂的。而且我现在正在回答同样的你为什么不的问题......现实情况是,推理方案总是有限制的;你要选择的是边界。最好选择干净,清晰的限制(可以在这些情况下使用它)而不是模糊限制。

You might say, then, "well, only make it work if they are the same type." We could do that, but now the boundary of when you can use inference and when not is even more complicated. And I'd be answering the same sort of "why don't you" question right now anyway ... The reality is that inference schemes always have limits; what you get to pick is the boundary. Better to pick clean, clear limits ("can use it in these contexts") than fuzzy ones.

这篇关于为什么不允许使用'var'的复合定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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