c# 这些声明之间有什么区别 1- class objClass;和 2- class objClass = null
c# Is there any difference between these declarations 1- class objClass; and 2- class objClass = null
这些声明有什么区别吗?
Animal animal;
Animal animal1 = null;
不,没有任何显着差异。最后,在运行时,您将有一个名为 animal
类型为 Animal
的变量,其值在定义时为 null
,稍后您将在逻辑上设置它的值为非 null
值,以便使用它。
但是,有些人会选择第一个而不是第二个声明,反之亦然。此外,有些人会争辩说,在第二种情况下分配 null
是多余的。例如,如果您使用 ReSharper,我想您会注意到一条关于在此处设置 null
.
冗余的消息
最后但同样重要的是,我假设您定义了一个 Animal
类型的变量,稍后您尝试设置它的值(我指的是第一种情况)。如果是这样的话,你的状态就很好。否则,如果您有以下代码段:
Animal animal;
if(animal==null)
{
}
您可能会在编译前收到警告和编译错误,描述如下:
Use of unassigned local variable 'animal'
如果您只声明了变量而从未使用过它,您会收到一条警告,说明如下:
The variable 'animal' is declared but never used
以上都是指局部变量的情况,如果我们是在class变量的情况下,那么事情就有点不同了。如果您创建控制台应用程序并且您有以下代码段:
class Program
{
static Animal animal;
static void Main(string[] args)
{
if(animal==null)
{
}
}
}
您将不会遇到任何编译错误。您将仅收到包含以下描述的警告:
Field 'Program.animal' is never assigned to, and will always have its default value null
根据 C# 规范,基于 context
存在差异。在 method
的上下文中,编译器可以证明第一个 animal
没有被赋值,因此可以在使用它的下一行生成编译器错误。如果 C# 编译器可以证明未分配,则 C# 编译器将不允许您使用方法变量。
但是,如果animal
是一个Class字段,它将自动初始化为默认值并且编译器不会产生错误。
以下是 C# 规范:
5.3 Definite assignment
At a given location in the executable code of a function member, a
variable is said to be definitely assigned if the compiler can prove,
by a particular static flow analysis (§5.3.3), that the variable has
been automatically initialized or has been the target of at least one
assignment.
因此,首先,编译器会生成一个 "Use of an unassigned local variable"
。而对于第二个,您显式地将变量分配给 null
,因此编译器应该可以接受。
这些声明有什么区别吗?
Animal animal;
Animal animal1 = null;
不,没有任何显着差异。最后,在运行时,您将有一个名为 animal
类型为 Animal
的变量,其值在定义时为 null
,稍后您将在逻辑上设置它的值为非 null
值,以便使用它。
但是,有些人会选择第一个而不是第二个声明,反之亦然。此外,有些人会争辩说,在第二种情况下分配 null
是多余的。例如,如果您使用 ReSharper,我想您会注意到一条关于在此处设置 null
.
最后但同样重要的是,我假设您定义了一个 Animal
类型的变量,稍后您尝试设置它的值(我指的是第一种情况)。如果是这样的话,你的状态就很好。否则,如果您有以下代码段:
Animal animal;
if(animal==null)
{
}
您可能会在编译前收到警告和编译错误,描述如下:
Use of unassigned local variable 'animal'
如果您只声明了变量而从未使用过它,您会收到一条警告,说明如下:
The variable 'animal' is declared but never used
以上都是指局部变量的情况,如果我们是在class变量的情况下,那么事情就有点不同了。如果您创建控制台应用程序并且您有以下代码段:
class Program
{
static Animal animal;
static void Main(string[] args)
{
if(animal==null)
{
}
}
}
您将不会遇到任何编译错误。您将仅收到包含以下描述的警告:
Field 'Program.animal' is never assigned to, and will always have its default value null
根据 C# 规范,基于 context
存在差异。在 method
的上下文中,编译器可以证明第一个 animal
没有被赋值,因此可以在使用它的下一行生成编译器错误。如果 C# 编译器可以证明未分配,则 C# 编译器将不允许您使用方法变量。
但是,如果animal
是一个Class字段,它将自动初始化为默认值并且编译器不会产生错误。
以下是 C# 规范:
5.3 Definite assignment
At a given location in the executable code of a function member, a variable is said to be definitely assigned if the compiler can prove, by a particular static flow analysis (§5.3.3), that the variable has been automatically initialized or has been the target of at least one assignment.
因此,首先,编译器会生成一个 "Use of an unassigned local variable"
。而对于第二个,您显式地将变量分配给 null
,因此编译器应该可以接受。