C# 静态方法和属性 图书管理

运行效果

添加4本书后:
C# 静态方法和属性 图书管理
点击“统计”后,输出书名以及价格:
C# 静态方法和属性 图书管理

代码

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;//统计目前有多少本书 同一类的对象有多少个 每点一次添加按钮 计数器+1

        public 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是静态变量 所以不用加this
            if (type == Type.Novel) novel++;
        }

        //静态构造函数 设置两个变量的默认值
        static Books()
        {
            compute = 0;
            novel = 0;
        }

        //静态方法 返回计算机图书数量
        public static int NumCompute()
        {
            return compute;
        }

        //静态方法属性 返回小说类图书数量
        public static int NumNovel
        {
            get { return novel; }
        }
    }
}