C#这是初始化器真是多余? [英] C# Is this initialiser really redundant?

查看:88
本文介绍了C#这是初始化器真是多余?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下面的代码行:

var dmrReceived = new DownloadMessagesReport();



和StyleCop的是ReSharper的建议我删除冗余初始化。但是,如果我用

StyleCop and ReSharper are suggesting I remove the redundant initializer. However if I replace it with

DownloadMessagesReport dmrReceived;



这肯定会产生不设置到对象的实例的对象引用?我使用.NET 3.5。 ?难道你不再必须手动来实例化对象。

surely this will generate an object reference not set to an instance of an object? I am using .NET 3.5. Do you no longer manually have to instantiate objects?

这下面下一行是:

dmrReceived = dc.DownloadNewMessages(param, param2, param3);



值得注意的是 DC 是类从WCF服务生成的。因此, DownloadNewMessages 是一个WCF Web服务方法。

It's worth noting that dc is a class generated from a WCF service. So DownloadNewMessages is a WCF web service method.

推荐答案

如果它是一个场,它会自动初始化为它的默认值 - 无效作为引用类型。鉴于 VAR 不过,我猜这不是,那你实际上实例化在你的代码反正进一步下跌,从而放弃您在此处实例化的价值。不需要初始化,其中它的声明的变量。如果你想使用 VAR 你这样做,但我建议你把它声明,你居然第一次使用它。

If it's a field, it will be automatically initialised to its default value - null for a reference type. Given the var however, I'm guessing it's not, and that you're actually instantiating it further down in your code anyway, thereby discarding the value you have instantiated here. You don't need to initialise a variable where it's declared. If you want to use var you do, but then I'd recommend you declare it where you actually first use it.

这篇关于C#这是初始化器真是多余?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆