为什么不C#默认为null未分配的局部变量? [英] Why doesn't C# default to null for unassigned local variables?

查看:115
本文介绍了为什么不C#默认为null未分配的局部变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有这样的事情:

public IOrder SomeMethodOnAnOrderClass()
{
   IOrder myOrder = null;

   if (SomeOtherOrder != null)
   {
       myOrder = SomeOtherOrder.MethodThatCreatesACopy();        
   }

   return myOrder;
}



没C#的厂商为什么需要明确的组 myOrder

时有过,你会想情况离开它未分配?

Is there ever a case where you would want to leave it unassigned?

是否设置为NULL与它相关的成本?这样,你会不会希望总是设置为null未分配的变量? (即使他们以后设置为别的东西。)

Does the setting to null have a cost associated with it? Such that you would not want to always have unassigned variables set to null? (Even if they are later set to something else.)

或者是需要确保你已经点缀所有的我的,穿过你的所有t?

Or is it required to make sure you have "dotted all your i's and crossed all your t's"?

还是有其他原因?

推荐答案

他们的的默认,或者更准确的说,你的对象的默认设置为的返回值默认(T) ,这是值类型不同。

They do default to null or, more accurately, your objects default to the value returned by default(T), which is different for value types.

这是一个特点。有因使用未初始化变量的程序员在野外错误的种种。并非所有的语言给你这样的事情,例如定义良好的行为(你知道你是谁...)。

This is a feature. There are all sorts of bugs in the wild caused by programmers using uninitialized variables. Not all languages give you such well defined behavior for this sort of thing (you know who you are...).

显然,你没有经历过呢。快乐和接受,编译器帮助你写出更好的代码。

Apparently you haven't experienced that yet. Be happy and accept that the compiler is helping you to write better code.

这篇关于为什么不C#默认为null未分配的局部变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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