C# struct 结构与类 class 的区别

结构与类共享大多数相同的语法,但结构比类受到的限制更多:

  • 在结构声明中,除非字段被声明为 const 或 static,否则无法初始化。

  • 结构不能声明默认构造函数(没有参数的构造函数)或析构函数。

  • 结构在赋值时进行复制。 将结构赋值给新变量时,将复制所有数据,并且对新副本所做的任何修改不会更改原始副本的数据。 在使用值类型的集合(如 Dictionary<string, myStruct>)时,请务必记住这一点。

  • 结构是值类型,而类是引用类型。

  • 与类不同,结构的实例化可以不使用 new 运算符。

  • 结构可以声明带参数的构造函数。

  • 一个结构不能从另一个结构或类继承,而且不能作为一个类的基。 所有结构都直接继承自 System.ValueType,后者继承自 System.Object。

  • 结构可以实现接口。

  • 结构可用作可以为 null 的类型,因而可向其赋 null 值。

示例如下:

using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            Person p1 = new Person("Alex", 9);
            Person.Name = "csw";//在结构声明中,除非字段被声明为 const 或 static,否则无法初始化。
            Console.ReadLine();
        }
    }

    public struct Person
    {
        //在结构声明中,除非字段被声明为 const 或 static,否则无法初始化。
        public static string Name = "ni";
        public int Age;
        //结构不能声明默认构造函数(没有参数的构造函数)或析构函数。
        //public Person()
        //{
        //}
        public Person(string name, int age)
        {
            Name = name;
            Age = age;
        }
    }
}
posted @ 2020-12-27 21:34  陈胜威  阅读(86)  评论(0编辑  收藏  举报