为什么我在使用前进行实例化

我不明白为什么或如何能够实例化一个变量并在类的开头没有赋值给它,但是一旦我进入类的编码,我就可以分配它来使用它。 例如在Unity中,我可以:

public class MapGenerator : MonoBehaviour { // right here I can instantiate the variable... public int width; public int height; // and then here I actually use it!! void GenerateMap() { map = new int[width,height]; RandomFillMap(); 

有人可以帮我解决这个问题吗?

JSL§4.12.5规定:

程序中的每个变量在使用其值之前必须具有值:

每个类变量,实例变量或数组组件在创建时都使用默认值进行初始化(§15.9,§15.10):

对于type字节,默认值为零,即(byte)0的值。

对于short类型,默认值为零,即(short)0的值。

对于int类型,默认值为零,即0。

对于long类型,默认值为零,即0L。

对于float类型,默认值为正零,即0.0f。

对于double类型,默认值为正零,即0.0d。

对于char类型,默认值为空字符,即’\ u0000’。

对于boolean类型,默认值为false。

对于所有引用类型(第4.3节),默认值为null。

您隐式使用的代码在Java中执行此操作:

 public int width; public int height; public MapGenerator() { // Constructor width = 0; height = 0; } void GenerateMap() { map = new int[width,height]; } 

我假设C#做了类似的事情。

值类型(C#参考)

每个值类型都有一个隐式默认构造函数,用于初始化该类型的默认值。

笔记:

  • 请注意初始化程序仅针对类成员运行。
  • 必须在使用之前初始化局部变量。

类型的默认值:

 bool: false byte: 0 char: '\0' decimal: 0.0M double: 0.0D enum: The value produced by the expression (E)0, where E is the enum identifier. float: 0.0F int: 0 long: 0L sbyte: 0 short: 0 struct: The value produced by setting all value-type fields to their default values and all reference-type fields to null. uint: 0 ulong: 0 ushort: 0 

class级成员 – 好的

 public class Sample1 { int i; public void PrintI() { //Prints 0 Console.WriteLine(i.ToString()); } } 

局部变量 – 错误

 public class Sample2 { public void PrintI() { int i; //Compile Error: Use of unassigned local variable 'i' Console.WriteLine(i.ToString()); } } 

这是值类型和引用类型之间的差异。

值类型(通过值传递)就是值。 引用类型是指值所在的位置。

所有类型都有一个默认值,对于引用类型,它是null,你可以想到“引用Nothing”,对于它不能的值类型,值不能为null,所以有一个默认值。

这里它的工作原理是因为int是一个值类型,这意味着即使是unitialized它也有一个默认值(对于值为0的所有数字类型),如果它是一个引用类型,当你尝试使用它时,你会得到一个NullReferenceException未初始化。

例如:

  public class Player { public string Name; } int i; // This is the same as int i = 0 as default(int) == 0 i.ToString(); // does not crash as i has a default value; Player p; // This is a reference type, the value fo default(Player) is null p.ToString(); // This will crash with a NullReferenceException as p was never initialized and you're effectivelly calling a method on "null". 

正如那些家伙所说..每个变量类型都有默认值…如果你没有给变量赋值,那么它将被赋予默认值……但是如果你想给变量另一个在创建对象或实例化它的那一刻,你可以使用像这样的构造函数

 public class MapGenerator { public int width; public int height; public MapGenerator(int Con_width, int Con_height) { width = Con_width; height = Con_height; } } 

现在,您创建的类的任何对象都必须具有宽度和高度的值

 MapGenerator mymap = new MapGenerator(200,200); 

现在,如果你尝试了通常的对象

  MapGenerator mymap = new MapGenerator(); 

它会给你一个错误,因为你将这个默认约束器更改为新的自定义约束器