我经常在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?
仅当您没有立即获得该值时.例如:
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)); }
VS
for (int i = 0; i < 10; i++) { int x = SomeFunction(); actions.Add(() => Console.WriteLine(x)); }
在第一个片段中,每个委托将捕获相同的变量,因此它们都可以有效地看到SomeFunction返回的最后一个值.在第二个片段中,每个代表将捕获x的单独“实例”.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。