加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 为什么在一行中声明一个变量,并在下一行中分配它?

发布时间:2020-12-15 20:50:19 所属栏目:百科 来源:网络整理
导读:我经常在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;DataTabl
我经常在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的单独“实例”.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读