1、所有类型,只声明的时候都不分配内存。 直接使用编译器会报错,如输出操作这种。
2、值类型和string类型,在执行"="运算符的时候,这个运算符的重载函数会给左边的操作数重新申请一块内存,因此,若左操作数之前没有分配内存,是可以执行=的,而且,这种情况下, “=”操作符执行的是深拷贝。
3、除了string外的引用类型,未分配内存时执行 = 运算符,也都OK,但是这时执行的是浅拷贝。
4、值类型和string类型,在执行 string []strA=new string[5]; 这个的时候,是给数组的所有元素分配内存的。 而其他引用类型,执行T[] tA =new T[5],这个时候,是不给数组元素分配内存的,直接访问数据元素会报错,若想在除string外的引用类型的数组定义的时候给元素分配内存,必须 T[] tA =new T[5]{new T(),new T(),new T(),new T(),new T()}这样的形式,大括号内需要有构造函数
5、引用类型定义的时候,使用null来初始化,分两种情况:
①、string对象,使用null或者string.Empty初始化,是分配内存的,如string str=null; 之后输出str,是OK的
②、除string外的其他引用类型,使用null初始化,是不分配内存的,对其进行引用,编译会报错
测试代码如下:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Test14
{
class MyClass
{
public int x=0 ;
public MyClass()
{
x = -1;
}
public MyClass(int y)
{
x = y;
}
}
class Program
{
static void Main(string[] args)
{
string str1 = "hello";
str1 += " world";
Console.WriteLine(str1);
//Console.WriteLine();
string str2 = str1; //这个时候,是给str2分配了全新的内存,将str1的值拷贝到str2的内存里
Console.WriteLine(str2);
str2 = "111";
Console.WriteLine(str1);
Console.WriteLine(str2);
string str3; //执行本步,是不会给str3分配内存的
//Console.WriteLine(str3); //这样会报错,因为str3没有分配内存
str3 = str1; //这里不报错,是因为本步在执行 = 的重载函数的时候,先给lhs分配了内存
Console.WriteLine(str3);
str3 = "333";
Console.WriteLine(str3);
int i1;
//Console.WriteLine(i1); //会报错
i1 = 5; //这里不报错,是因为本步在执行 = 的重载函数的时候,先给lhs分配了内存
MyClass mc;
//Console.WriteLine(mc.x); //这样会报错
MyClass mc2 = new MyClass();
mc = mc2;
Console.WriteLine(mc.x); //这样OK
mc.x = 19;
Console.WriteLine(mc2.x); //这样OK
string []strA1 = new string[5]; //吊炸了,这里已经给strA1的各个元素分配内存了
//strA1[0] = "hello"; //这样不报错,是因为本步在执行 = 的重载函数的时候,先给lhs分配了内存
Console.WriteLine(strA1[0]); //不报错
Console.WriteLine(strA1[1]); //报错
int[] iA1 = new int[5]; //吊炸,这也分配内存了
Console.WriteLine(iA1[0]);
//MyClass[] mcA1 = new MyClass[3]; //这样就会报错了,这里并没有给mcA1的各个元素分配内存
MyClass[] mcA1 = new MyClass[3] { new MyClass(1), new MyClass(2), new MyClass(3) }; //这样就不报错
Console.WriteLine(mcA1[0].x);
//string str;
//Console.WriteLine(str); //报错
string str = null;
Console.WriteLine(str); //不报错,可以运行
//string str=string.Empty;
//Console.WriteLine(str); //不报错,可以运行
}
}
}