class Program
{
static void Main(string[] args)
{
Card[] card = new Card[10];
if (card[0] == null)
{
Console.WriteLine("null");
}
else
{
Console.WriteLine("not null");
}
for (int i = 0; i < card.Length; i++)
{
card[i] = new Card();
}
if (card[0] == null)
{
Console.WriteLine("null");
}
else
{
Console.WriteLine("not null");
}
}
}为什么这个
Card[] card = new Card[10];
if (card[0] == null)
{
Console.WriteLine("null");
}
是null的
而下面那个for (int i = 0; i < card.Length; i++)
{
card[i] = new Card();
}
if (card[0] == null)
{
Console.WriteLine("null");
}
else
{
Console.WriteLine("not null");
}
不是null的 求详解!!!!
类
class Card
{
public int value;
}
第二次测试,Card[0]已赋值,所以为not null
就赋值了,所以不是null
但还没有学生入座你for一下判断是否座位上有学生 当然是null下面你为每个座位 new 一个学生 入座
再for 当然是not null 啦Card[] card = new Card[10]; //你只是声明一个数组还有为这个数组分配空间
但还没有为数组中的每个对象实例化一个对象
for (int i = 0; i < card.Length; i++)
{
card[i] = new Card();//为数组中的每个对象实例化一个对象 分配了内存 就不再是null
}
第二次 card[i] = new Card(); 时card[] 为字符数组的某一个 里面的值位 实例化的 Card()值。 所以 not null
下面这个用for循环赋值了(数组里的每一个元素都是Card实例)
for (int i = 0; i < card.Length; i++)
{
card[i] = new Card();
}
card[i] = new card()后
card[i]里面已经不是null了,已经是默认构造函数的实体了
没实例前是没进行任何操作。
new后就有了
时,开始实例化了,已经给card[i] 分配内存了。