欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-12-24 19:34:03
结构体 值类型,可装/拆箱 可实现接口,不能派生自类/结构体(不能有基类,不能有基结构体) 不能有显式无参构造器 struct Student{ public int ID {get;set;} public string Name {get;set;} } //stu1是一个局部变量,分配在mai ......

结构体

  • 值类型,可装/拆箱
  • 可实现接口,不能派生自类/结构体(不能有基类,不能有基结构体)
  • 不能有显式无参构造器
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;}
}

上一篇:

下一篇: