Struct就像是輕量版本的Class~ 但它們間還是有幾點差異性~
我們今天就來看看Struct跟Class的差異性吧~
學習目標: Struct and Class的概念及實務
學習難度: ☆☆☆
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