C# 静态方法和属性 图书管理
生活随笔
收集整理的這篇文章主要介紹了
C# 静态方法和属性 图书管理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
運行效果
添加4本書后:
點擊“統計”后,輸出書名以及價格:
代碼
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms;namespace 靜態 {public partial class Form1 : Form//冒號表示繼承 Form表示基類{public Form1(){InitializeComponent();}Books[] bs = new Books[100];//------?private void button1_Click(object sender, EventArgs e){Type type = comboBox1.SelectedIndex == 0 ? Type.Compute : Type.Novel;//因為只有兩個選項 所以用?: 臨時存儲書類型double price = Convert.ToDouble(textBox2.Text);//臨時存儲書價格bs[Books.count] = new Books(textBox1.Text, type, price);Books.count++;textBox3.Text = string.Format("添加成功:一共{0}本書", Books.count);}private void button2_Click(object sender, EventArgs e){textBox3.Text = string.Format("計算機類圖書總數:{0}本書\r\n", Books.NumCompute());textBox3.Text += string.Format("小說類圖書總數:{0}本書\r\n\r\n", Books.NumNovel);textBox3.Text += string.Format("圖書名單如下:\r\n");foreach (Books b in bs){if (b != null){textBox3.Text += string.Format("《{0}》 {1}元\r\n", b.title,b.price);}}}}public enum Type { Compute, Novel };//枚舉類型public class Books{private static int compute;private static int novel;public static int count;//統計目前有多少本書 同一類的對象有多少個 每點一次添加按鈕 計數器+1public string title;public Type type;public double price;//構造函數public Books(string title, Type type, double price)//參數調用時才分配存儲器{this.title = title;//this表示當前正在執行操作的對象this.type = type;this.price = price;if (type == Type.Compute) compute++;//因為compute是靜態變量 所以不用加thisif (type == Type.Novel) novel++;}//靜態構造函數 設置兩個變量的默認值static Books(){compute = 0;novel = 0;}//靜態方法 返回計算機圖書數量public static int NumCompute(){return compute;}//靜態方法屬性 返回小說類圖書數量public static int NumNovel{get { return novel; }}} }總結
以上是生活随笔為你收集整理的C# 静态方法和属性 图书管理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# 类的派生 输出个人信息
- 下一篇: 【算法设计与分析】最长公共子序列问题 动