VAR"&的使用QUOT;类型变量声明 [英] Use of "var" type in variable declaration
问题描述
我们的内部审计建议我们使用,而不是使用关键字明确的变量类型声明 VAR
。他们认为,使用变种
可能导致在某些情况下意外的结果。
Our internal audit suggests us to use explicit variable type declaration instead of using the keyword var
. They argue that using of var
"may lead to unexpected results in some cases".
我不知道明确的类型声明,并使用变种之间的差异
一旦code编译成MSIL。
I am not aware of any difference between explicit type declaration and using of var
once the code is compiled to MSIL.
审核员是一个受人尊敬的职业,所以我不能简单地拒绝这样的建议。
The auditor is a respected professional so I cannot simply refuse such a suggestion.
推荐答案
这个怎么样?
double GetTheNumber()
{
// get the important number from somewhere
}
和其他地方的话...
And then elsewhere...
var theNumber = GetTheNumber();
DoSomethingImportant(theNumber / 5);
然后,在未来的某个时刻,有人注意到 GetTheNumber
只会返回整数所以refactors它返回 INT
,而不是双击
。
And then, at some point in the future, somebody notices that GetTheNumber
only ever returns whole numbers so refactors it to return int
rather than double
.
砰!没有编译器错误和你开始看到意想不到的效果,因为什么是previously浮点运算现已成为整数运算,却没有人注意到。
Bang! No compiler errors and you start seeing unexpected results, because what was previously floating-point arithmetic has now become integer arithmetic without anybody noticing.
话虽如此,这样的事情的应的被你的单元测试等抓住了,但它仍然是一个潜在的疑难杂症。
Having said that, this sort of thing should be caught by your unit tests etc, but it's still a potential gotcha.
这篇关于VAR"&的使用QUOT;类型变量声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!