首页 > 代码库 > [c# 20问] 1. 何时使用class与struct

[c# 20问] 1. 何时使用class与struct

POINTS

struct为可以包含数据和函数的值类型

struct为值类型所以不需要堆(heap)而是在栈(stack)上分配空间

struct将数据直接存在struct中,而class只存引用类型的指针

struct适用于小的数据结构

struct会影响性能

struct可以使用new操作可以调用构造器,但是不会在heap上分配内存

struct的构造器只返回struct的值本身(通常分配在stack上)

使用class时,多个变量可以引用同一个对象

使用sturct每个变量都保存自己的数据拷贝,不会相互影响

struct不支持继承,sturct继承自object类型

DEMO
    class Program    {        class PointClass        {            public int x;            public int y;            public PointClass(int x, int y)            {                this.x = x;                this.y = y;            }        }        struct PointStruct        {            public int x;            public int y;            public PointStruct(int x, int y)            {                this.x = x;                this.y = y;            }        }        static void Main(string[] args)        {            PointStruct pointStruct = new PointStruct(10, 10);            Console.WriteLine("Initial struct values are {0},{1}", pointStruct.x, pointStruct.y);            ModifyStructPoint(pointStruct);            Console.WriteLine("After ModifyStructPoint, struct values are {0},{1}", pointStruct.x, pointStruct.y);            Console.WriteLine();            PointClass pointClass = new PointClass(10, 10);            Console.WriteLine("Initial Class values are {0},{1}", pointClass.x, pointClass.y);            ModifyClassPoint(pointClass);            Console.WriteLine("After ModifyClassPoint, class values are {0},{1}", pointClass.x, pointClass.y);            Console.ReadLine();        }        private static void ModifyStructPoint(PointStruct pointStruct)        {            pointStruct.x = 20;            pointStruct.y = 20;            Console.WriteLine("Modified Valuesare {0},{1}", pointStruct.x, pointStruct.y);        }        private static void ModifyClassPoint(PointClass pointClass)        {            pointClass.x = 20;            pointClass.y = 20;            Console.WriteLine("Modified Valuesare {0},{1}", pointClass.x, pointClass.y);        }    }