c# - struct和class的区别

1. struct不可以有无参数的构造函数
2. 如果struct存在构造函数,所有属性必须在构造函数中初始化
3. 不可以在struct中直接初始化属性
4. struct可以不使用new初始化
5. 若struct没有使用new初始化, 所有属性赋值之后, 对象才可以使用
6. struct不可被继承
7. struct可以实现接口(与class一致)
8. struct是值类型,class是引用类型

using System;

namespace StructDemo
{
    interface IPrintable
    {
        void Print();
    }

    // 7. struct可以实现接口
    public struct Person : IPrintable
    {
        // 1. struct不可以有无参数的构造函数

        // 2. 如果存在构造函数,所有属性必须在构造函数中初始化
        //public Person(string name, int age)
        //{
        //    Name = name;
        //    Age = age;
        //}

        public void Print()
        {
            Console.WriteLine("Name:" + Name + ", Age:" + Age);
        }

        public string Name;

        // 3. struct不可以直接初始化属性
        public int Age;
    }

    // 6. struct不可被继承
    //struct Student : Person
    //{
    //}

    class StructDiff
    {
        public static void Test()
        {
            // 4. struct可以不使用new初始化
            Person person;

            // 5. 若struct没有使用new初始化, 所有属性赋值之后, 对象才可以使用
            person.Name = "Peter";
            person.Age = 12;

            person.Print();

            // 8. struct是值类型,class是引用类型
        }
    }
}
发布了130 篇原创文章 · 获赞 20 · 访问量 30万+

猜你喜欢

转载自blog.csdn.net/yuxuac/article/details/103235703
今日推荐