C#类和结构的区别

类(class)和结构(struct)看起来功能差不多,但是内部还是有一些不同。

  1. 结构类型是值类型,类类型是引用类型。
  2. 凡是定义为结构的,都可以用类定义。
  3. 有些情况使用结构比使用类的执行效率高。

举例来说,我们现在需要十个点的坐标,在调用时需要初始化,现在来看一看两者都是怎么初始化的。

//----------------ClassPoint.cs------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassStructExample
{
    class ClassPoint
    {
        public int x, y;
        public ClassPoint(int x,int y)
        {
            this.x = x;
            this.y = y;
        }
    }
}
//----------------StructPoint.cs------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassStructExample
{
    struct StructPoint
    {
        public int x, y;
        public StructPoint(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }
}
//----------------Program.cs------------------
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassStructExample
{
    class Program
    {
        static void Main(string[] args)
        {
            ClassPoint[] p = new ClassPoint[10];
            for (int i = 0; i < p.Length; i++)
            {
                //必须为每个元素创建一个对象
                p[i] = new ClassPoint(i,i);
                Console.Write("({0},{1})",p[i].x,p[i].y);
            }
            Console.WriteLine();

            StructPoint[] sp = new StructPoint[10];
            for (int i = 0; i < sp.Length; i++)
            {
                //sp[i] = new StructPoint(i, i);
                //不用为每个元素创建一个对象,当然也可以创建,如上一行代码
                Console.Write("({0},{1})", sp[i].x, sp[i].y);
            }
            Console.WriteLine();
        }
    }
}

输出结果:

在这个程序中,创建并初始化了一个含有10个点的数组。对于作为类实现的Point,出现了11个实例对象,包括声明数组的一个对象p,10个数组元素每个都要创建一个对象。而用结构实现Point,只需要创建一个对象。

如果数组是1000*1000,那么两者的程序执行效率会很不同。

猜你喜欢

转载自blog.csdn.net/HB_Programmer/article/details/81843117