引用类型
程序员文章站
2022-06-10 13:37:01
...
using System;
namespace Objects
{
class Program
{
static void Main(string[] args)
{
Student student1=new Student(1);
Student student2 = student1;
Student student3=new Student(2);
Console.WriteLine("student2.StudentId:" + student2.StudentId);//1
Console.ReadKey();
}
}
class Student
{
public int StudentId;
public Student(int studentId)
{
this.StudentId = studentId;
}
}
}
01.当 student1的变量发生改变时,student2也随之改变
class Program
{
static void Main(string[] args)
{
Student student1=new Student(1);
Student student2 = student1;
Student student3=new Student(2);
Console.WriteLine("student2.StudentId:" + student2.StudentId);//1
student1.StudentId = 3;
Console.WriteLine("student2.StudentId:" + student2.StudentId);//3
Console.ReadKey();
}
}
class Student
{
public int StudentId;
public Student(int studentId)
{
this.StudentId = studentId;
}
}
02.new关键字:
创建特定对象的实例并返回其引用地址
03.我们将student3的变量赋值给了student1,那么这段代码执行的是将student3对应的ID(引用地址)以副本的方式给了student1。
class Program
{
static void Main(string[] args)
{
Student student1=new Student(1);
Student student2 = student1;
Student student3=new Student(2);
Console.WriteLine("student2.StudentId:" + student2.StudentId);
// student1 和 student2的引用地址是都是1001,地址是通过副本进行传递的当student1的地址发生改变并不会影响student2的地址
student1 = student3;
Console.WriteLine("student2.StudentId:" + student2.StudentId);
Console.WriteLine("student1.StudentId: "+student1.StudentId);
Console.ReadKey();
}
}
class Student
{
public int StudentId;
public Student(int studentId)
{
this.StudentId = studentId;
}
}