看範例學C#-09 struct結構

  • 14191
  • 0
  • C#
  • 2011-10-06

看範例學C#-09 struct結構

struct是一種用來宣告結構的關鍵字,在結構中包含相關 變數,可將結構視為變數群組

宣告方式:

[存取修飾詞] struct [結構名稱]

{

[存取修飾詞]  [資料型別] [變數名稱]

}

存取修飾詞請參考MSDN

資料型別請參考MSDN

使用方式:

結構名稱.變數名稱="abc"//字串型別要用雙引號包,數字型別 直接打數字

 

以下為struct範例程式碼及註解

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Struct_ex
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        public struct Phone_Book
        {
            public string Name;
            public string Number;
            public DateTime PublishDate;
            public int Cost;
        }
        private void btnAdd_Click(object sender, EventArgs e)
        {
            Phone_Book PB;
            PB.Name = cName.Text;
            PB.Number = txtAuthor.Text;
            PB.PublishDate = Birthday.Value;
            string msg = "";
            msg = msg + "姓名:" + PB.Name + "\n";
            msg = msg + "電話:" + PB.Number + "\n";
            msg = msg + "出生日期:" + PB.PublishDate.ToShortDateString() + "\n";
            MessageBox.Show(msg, "struct範例");
        }
    }
}

ex09.rar


如有錯誤 歡迎指正