iT邦幫忙

2026 iThome 鐵人賽

DAY 20
0

什麼是 靜態屬性

屬於 class 本身的屬性


使用方法

Video模板:

using System;
namespace ConsoleApp1
{
class Video
{
public string title;
public string author;
public string type;
/title、author、type 屬於物件屬性
public static int video_count = 0; /屬於 Video class 的靜態屬性
     public Person( string title, string author, string type )
     {
         this.title = title;
         this.author = author;
         this.type = type;
         video_count++;
     }
}
}

原本的資料型態:

using System;
using ConsoleApp1
Console.WriteLine( Video.video_count ); /video_count這個屬性屬於video這個class本身
Video video1 = new Vedio( “真D舒服”, “小白”, “教育” );
Console.WriteLine( Video.video_count );
Video video2 = new Vedio( “有那麼舒服”, “小黑”, “娛樂” );
Console.WriteLine( Video.video_count );

第一行WriteLine因為還沒有創建Video的物件,所以顯示 0,第二行創建了 video1 顯示 1,第三行創建了 video1 顯示 2,最終顯示 0 1 2

class名稱 . static 的名稱


如果想要video1物件來取得video_count屬性

public Person( string title, string author, string type )
{
this.title = title;
this.author = author;
this.type = type;
video_count++;
}
public int getVideoCount( )
{
return video_count;
}

原本的資料型態:

Console.WriteLine( Video.video_count );
Video video1 = new Vedio( “真D舒服”, “小白”, “教育” );
Console.WriteLine( Video.video_count );
Video video2 = new Vedio( “有那麼舒服”, “小黑”, “娛樂” );
Console.WriteLine( video1.getVideoCount( ) );

屬性寫getVideoCount( ),最後會回傳給 video_count
結果同樣顯示 0 1 2


心得:

今天學習了如何使用靜態屬性,可以看到程式碼與之前的大同小異,但卻可以拆成非常細來解析,這也是學習程式的困難之處。明天會學習到同樣是靜態的method與class,我們明天見~


參考影片

【C#】3小時初學者教學 |Csharp | C# 教學 | C# 入門 | C++++
YouTube頻道:GrandmaCan -我阿嬤都會
影片段落: 3:03:23 ~ 3:08:04 (時間段已設定好)
Yes


上一篇
【Day19】getter、setter
系列文
從 Hello World 學習 C#,到看懂AI生成的遊戲程式碼 共 20 篇
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言