值类型和引用类型
面试的时候会经常被问道这些基础问题,实习一段时间后回来把Timothy老师的课程整体过一遍后发现他在这一块讲的很是精彩:
C#是强类型语言,所以分为值类型和引用类型,以下是他们在栈内存、堆内存中的划分情况以及他们实例改变后的值:
类类型实例:
using System; namespace TheDifferentOfReferenceTypeAndValueType { class Program { static void Main(string[] args) { Student stu1 = new Student() { ID = 1001, Name = "小明" }; Student stu2 = stu1; stu2.ID = 1002; stu2.Name = "小红"; Console.WriteLine(stu2.ID + " " + stu2.Name); Console.WriteLine(stu1.ID + " " + stu1.Name); } } class Student { public int ID { get; set; } public string Name { get; set; } } }
运行结果:
结构体类型实例:
using System;
namespace TheDifferentOfReferenceTypeAndValueType
{
class Program
{
static void Main(string[] args)
{
Teacher teacher1 = new Teacher() { ID = 001, Name = "英语老师" };
Teacher teacher2 = teacher1;
teacher2.ID = 002;
teacher2.Name = "体育老师";
Console.WriteLine(teacher1.ID + " " + teacher1.Name);
Console.WriteLine(teacher2.ID + " " + teacher2.Name);
}
}
struct Teacher
{
public int ID { get; set; }
public string Name { get; set; }
}
}
运行结果:
以上对比可知:引用类型的变量(在栈内存中)记录的是其实例(在堆内存中)的起始地址,而值类型的变量就是堆内存的起始地址;
所以上述的值类型的Student结构体类型就跟int a =1;是一个道理;
如果还不懂没关系,看下面这张内存的划分图就知道了:
或者我之前做的笔记截图:
注意这里的string是类类型跟int不一样;