[C#] การใช้ Function ใช้ argument แบบ Array และ Struct

โค้ด

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string strOut = "";
            Random obj = new Random();
            int[] myArray = new int[8];
            for (int i = 0; i < myArray.Length; i++)
            {
                myArray[i] = obj.Next(10);
                strOut += "MyArray[" + i.ToString() + "] = " + myArray[i].ToString() + "\r\n";
            }
            strOut += "Summation all values in the Array = " + SumArray(myArray).ToString();
            MessageBox.Show(strOut, "Pass Array");

        }

        private int SumArray(int[] pa)
        {
            int result = 0;
            for (int i = 0; i < pa.Length; i++)
            {
                result += pa[i];
            }
            return result; 
        }

        public struct MyStruct
        {
            public string Name;
            public string Gender;
            public bool Married;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            MyStruct myRec = new MyStruct();
            if(tbxName.Text != "")
            {
                myRec.Name = tbxName.Text;
            }
            else
            {
                MessageBox.Show("กรุณาใส่ชื่อด้วย");
                return;
            }
            if(rbMale.Checked == true)
            {
                myRec.Gender = rbMale.Text;
            }
            else if (rbFemale.Checked == true)
            {
                myRec.Gender = rbFemale.Text;
            }
            else
            {
                MessageBox.Show("กรุณาเลือกเพศด้วย");
                return;
            }
            if (ckbMarried.Checked == true)
            {
                myRec.Married = true;
            }
            else
            {
                myRec.Married = false;
            }
            MessageBox.Show(getStruct(myRec), "Pass struct");
        }

        private string getStruct(MyStruct rec)
        {
            string result ="";
            result += "Name: " + rec.Name + " | ";
            result += "Gender: " + rec.Gender + " | ";
            result += "Married: " + rec.Married;
            return result;
        }

    }
}
Previous
Next Post »