Home [C# 筆記] Class 類別
Post
Cancel

[C# 筆記] Class 類別

物件導向

物件導向過程 => 物件導向

物件導向過程:物件導向是完成這件事情的過程,強調的是完成這件事情的動作

把大象放到冰箱裡

  1. 打開冰箱
  2. 把大象塞進去
  3. 關閉冰箱門

強調的是過程

class 類別

語法:

1
2
3
4
5
6
[public] class 類名
{
    字段; //儲存數據
    屬性;
    方法;
}
1
2
3
4
5
class TestClass
{
    // Methods, properties, fields, events, delegates
    // and nested classes go here.
}
1
2
3
4
5
6
7
8
9
10
11
12
public class Person
{
    //fields字段(欄位)
    private string _name; 
    private int _age;
    private char _gender;

    //method
    public void SayHello() { 
        Console.WriteLine("Hello");
    }
}

寫好一個類別之後,我們需要創建這個類的對象(物件),
創建這個類的對象過程,稱之為類的實體化。

  • 使用關鍵字new
  • this:表示當前這個類別的對象。
  • 類別是不佔內存的,而對象(物件)是佔內存的。
1
2
Person person; //沒有開空間,不佔內存
Person person = new Person(); //有開空間,有佔內存

keywords/class

This post is licensed under CC BY 4.0 by the author.