为什么是必要的声明必要、声明、为什么是

2023-09-04 07:18:55 作者:岁月反驳

我现任教同事.Net和他问了我一个问题,难倒我。

I am currently teaching a colleague .Net and he asked me a question that stumped me.

我们为什么要申报吗?

如果VAR是隐式类型,为什么我们连申报吗?

if var is implicit typing, why do we have to even declare?

Animal animal = new Animal();

变为

var animal = new Animal();

可能成为

animal = new Animal();

的隐式类型仍然意味着这是一个静态类型变量。

The implicit typing would still mean that this is a statically typed variable.

如果两个不同的类型分配给该变量,如果它们不共享一个基础类,(除其它对象),这可能是一个编译错误。

If two different types are assigned to the variable, if they do not share a base class, (other than object), that could be a compiler error.

是否有技术原因,这件事情不能做或者是风格上我们喜欢havein

Is there a technical reason this could not be done or is it stylistically we like havein

推荐答案

当然,这的将会的可能。

我能想到的一些原因,你不希望这样的:

I can think of a few reasons you don't want this:

什么是你的变量的范围?尚不清楚,如果你不告诉编译器。请问动物的两种方法成为私有变量或两个方法范围的变量? 如果名称是什么一个错字?你永远不会知道。 如果你已经分配一个值,这个变量,然后尝试分配一个新的值,它是与上次不兼容(即JavaScript的方式)(学分的马里奥·斯托伊洛夫) What is the scope of your variable? Not clear if you don't tell the compiler. Will animals in two methods become a private variable or two method scoped variables? What if the name is a typo? You will never know. What if you already assigned a value to this variable and then try to assign a new value which is incompatible with the last (i.e javascript style) (credits to Mario Stoilov)