C#基础_学习笔记--结构体

结构体

  • 值类型,可装/拆箱
  • 可实现接口,不能派生自类/结构体(不能有基类,不能有基结构体)
  • 不能有显式无参构造器
struct Student{
    public int ID {get;set;}
    public string Name {get;set;}
}
//stu1是一个局部变量,分配在main函数的内存栈上,存的是Student类型的实例
Student stu1 = new Student(){
    ID = 101,
    Name = "Timtohy"
};
//装箱
object obj = stu1; //将stu1实例copy丢到内存“堆”里去,用obj这个变量来引用堆内存中的stu1实例
//拆箱
Student student2 = (Student)obj;
Console.WriteLine($"#{student2.ID} Name:{student2.Name}");//#101 Name:Timtohy

值类型与引用类型copy时不同

Student stu1 = new Student(){ID = 101,Name = "Timothy"};
Student stu2 = stu1;
stu2.ID = 1001;
stu2.Name = "Michael";
Console.WriteLine($"#{stu1.ID} Name:{stu1.Name}");//#101 Name:Timothy
Console.WriteLine($"#{stu2.ID} Name:{stu1.Name}");//#1001 Name:Michael

stu2和stu1是两个对象

结构体可以实现接口
interface ISpeak{
	void Speak();
}
struct Student:ISpeak{
    public int ID {get;set;}
    public string Name {get;set;}
    public void Speak(){
        Console.WriteLine($"I'm #{this.ID} student{this.Name}");
    }
}
结构体不能有基结构体
结构体不能有显示无参构造器
struct Student{
    public Student(){}//这样是错误的
    public Student(int id,string name){
        this.ID = id;
        this.Name = name;
    }//正确
    
    public int ID {get;set;}
    public string Name {get;set;}
}
posted @ 2021-06-07 10:33  三只小松鼠  阅读(62)  评论(2编辑  收藏  举报