【C#】Struct vs Class

Struct就像是轻量版本的Class~ 但它们间还是有几点差异性~

我们今天就来看看Struct跟Class的差异性吧~


学习目标: Struct and Class的概念及实务

学习难度: ☆☆☆


https://ithelp.ithome.com.tw/upload/images/20220409/20147886h9rdqD1T9a.png


Struct在以下情形时使用是一个不错的选择~

  • Struct表示单一值~ 例如~ 位置 ~

  • Struct中的值尽量是不可变~

  • Struct尽量不要频繁装箱~ 拆箱~


Struct实例 ~

    struct Location
    {
        public int x, y;
        public Location(int x, int y)
        {
            this.x = x;
            this.y = y;
        }
    }

    public class MainProgram
    {
        static void Main()
        {
            Location location = new Location(100,200);

            Console.WriteLine(location.x+","+location.y);
        }
    }

Class实例 ~

    class Shop
    {
        public string name;

        public int x, y;

        public Shop(int x, int y,string name)
        {
            this.x = x;
            
            this.y = y;
            
            this.name = name;
        }
    }

    public class MainProgram
    {
        static void Main()
        {
            Shop shop = new Shop(150,300,"KFC");

            Console.WriteLine(shop.x+","+ shop.y+ ","+shop.name);
        }
    }

参考资料:

https://www.c-sharpcorner.com/blogs/difference-between-struct-and-class-in-c-sharp

https://iter01.com/529880.html

https://dotblogs.com.tw/daniel/2018/02/22/135011


<<:  【C#】Abstract Class vs Interface

>>:  【C#】Delegate and Events

CLI名词解释

命令列介面命令列介面(英语:Command-Line Interface,缩写:CLI)是在图形使用...

Day-20 用 Pytorch 的最後一个块拼图

那我们已经在昨天说明了 Pytorch 的 Dataset 跟 DataLoader 要如何建立了...

认识强大的Python套件:Pandas(下)

今天我们接着继续和DataFrame继续奋斗!先把套件和档案载入: import pandas as...

【Day 20】QGIS + OSM + folium part 2

看看昨天的图层 我们将图层输出(Export)成 GeoJSON,点开来可以看到这些 json 的文...

Day01 前言x初识CTF

前言 大家好,我是 Yvonne,大家也可以叫我凡凡 :) 这次是我第一次参加 IT 邦帮忙铁人赛,...