[c# 20問] 1. 何時使用class與struct

來源:互聯網
上載者:User

標籤:style   blog   color   使用   資料   ar   div   line   

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);        }    }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.