我经常在 C# 代码中看到以下约定:
some_type val;
val = something;
喜欢
DataTable dt;
dt = some_function_returning_datatable();
或
DataTable dt = new DataTable();
dt = some_function_returning_datatable();
代替
some_type val = something;
DataTable dt = some_function_returning_datatable();
我最初认为这是您必须在范围顶部声明所有局部变量的日子遗留下来的习惯。但我学会了不要这么快就摒弃资深开发人员的习惯。
(在我的第 3 个代码部分,当我们先用 new
分配 dt
然后从函数分配时,不会浪费内存吗)
那么,是否有充分的理由在一行中声明,然后再赋值?
最佳答案
In my 3rd code section will it not be wastage of memory when we assign dt first with new and then from function
是的,确实如此。只是相对较小 - 创建一个无用的 DataTable
对象 - 但仍然很浪费和不清楚。
So, is there a good reason for declaring in one line, and assigning afterwards?
仅当您没有立即获得值(value)时。例如:
string x;
if (someCondition) {
// Do some work
x = someResult;
} else {
// Do some other work
x = someOtherResult;
}
通常可以使用条件运算符或将该代码提取到方法中来改进这一点。但有时情况并非如此。
对于简单的情况:
Foo x = SomeInitializationWithNoUsefulSideEffects();
x = SomeUsefulValue();
或者
Foo x;
x = SomeUsefulValue();
你应该绝对重构
Foo x = SomeUsefulValue();
另一种有趣的情况是声明点确实有所不同是在捕获的变量中,尽管通常不是它预期的方式:
int x;
for (int i = 0; i < 10; i++) {
x = SomeFunction();
actions.Add(() => Console.WriteLine(x));
}
对比
for (int i = 0; i < 10; i++) {
int x = SomeFunction();
actions.Add(() => Console.WriteLine(x));
}
在第一个代码段中,每个委托(delegate)将捕获相同的变量,因此它们都将有效地看到从 SomeFunction
返回的最后一个值。在第二个片段中,每个委托(delegate)将捕获 x
的单独“实例”。
关于c# - 为什么在一行中声明一个变量,然后在下一行赋值给它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10496938/