c# 结构体

本文详细介绍了C#中结构体的特性,包括结构体能够实现接口、不能作为父类被继承、不支持无参构造器但允许有参构造器的使用。
摘要由CSDN通过智能技术生成
using System;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            // student 分配在 栈上
            Student student = new Student() {ID = 101, Name = "ll"};
            // 装箱
            object obj = student;
            //拆箱
            Student s2 = (Student) obj;
            Console.WriteLine($"#{s2.ID}"); // #101

            Console.WriteLine("===============");
            // 引用类型复制的是地址
            // 值类型复制的是值
            Student stu1 = new Student() {ID = 101, Name = "ll"};
            Student stu2 = stu1;
            stu2.ID = 1001;
            stu2.Name = "zs";
            // ID:101,Name:ll
            Console.WriteLine($"ID:{stu1.ID},Name:{stu1.Name}");
            //ID:1001,Name:zs
            Console.WriteLine($"ID:{stu2.ID},Name:{stu2.Name}");
        }
    }

    /// <summary>
    /// 结构体类型是值类型
    /// </summary>
    struct Student
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
}

结构体可以实现接口

using System;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            // 引用类型复制的是地址
            // 值类型复制的是值
            Student stu1 = new Student() {ID = 101, Name = "ll"};
            Student stu2 = stu1;
            stu2.ID = 1001;
            stu2.Name = "zs";
            // I'm #101, Name:ll
            stu1.Sepak();
        }
    }

    interface ISpeak
    {
        void Sepak();
    }

    /// <summary>
    /// 结构体类型是值类型
    /// </summary>
    struct Student : ISpeak
    {
        public int ID { get; set; }
        public string Name { get; set; }

        public void Sepak()
        {
            Console.WriteLine($"I'm #{this.ID}, Name:{this.Name}");
        }
    }
}

结构体不能是父类,即不能被继承

在这里插入图片描述

结构体不能有显式的无参构造器

在这里插入图片描述

结构体可以有显式的有参构造器

using System;

namespace ConsoleApp4
{
    class Program
    {
        static void Main(string[] args)
        {
            // 引用类型复制的是地址
            // 值类型复制的是值
            Student stu1 = new Student(111, "lll") {ID = 222, Name = "sss"};
            //#ID:222, Name:sss
            Console.WriteLine($"#ID:{stu1.ID}, Name:{stu1.Name}");
        }
    }

    interface ISpeak
    {
        void Sepak();
    }

    /// <summary>
    /// 结构体类型是值类型,不是引用类型
    /// </summary>
    struct Student : ISpeak
    {
        public Student(int id, string name)
        {
            this.ID = id;
            this.Name = name;
        }

        public int ID { get; set; }
        public string Name { get; set; }

        public void Sepak()
        {
            Console.WriteLine($"I'm #{this.ID}, Name:{this.Name}");
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值