星期一, 6月 09, 2014

[C#] Function 回傳多值

在 MVA Twenty C# Questions Explained - [20 - How Can I Return Multiple Values From a Function in C Sharp] 中,直覺是利用 out 參數就可以作到,在課程中還有介紹利用 Stucts 來作到,是自己沒有想到的,在這裡作個記錄

out 範例:搜尋員工個人資料
using System.Data.SqlClient;

namespace WindowsFormsApplication1
{
    public partial class frmReturnMultiValue : Form
    {

        DataTable dt = new DataTable();

        private void frmReturnMultiValue_Load(object sender, EventArgs e)
        {
            dt.Columns.Add("EmpNO", typeof(int));
            dt.Columns.Add("EmpName", typeof(string));
            dt.Columns.Add("Birthday", typeof(DateTime));
            dt.Rows.Add(1, "張三", new DateTime(1981, 12, 1));
            dt.Rows.Add(2, "李四", new DateTime(1980, 1, 9));
            dt.Rows.Add(3, "王五", new DateTime(2014, 5, 5));

            if (dt.PrimaryKey.Length == 0) dt.Constraints.Add("PK", dt.Columns["EmpNO"], true);
        }

        public Boolean FuncOut(int EmpNO, out string EmpName, out DateTime? Birthday)
        {

            DataRow dr = dt.Rows.Find(EmpNO);
            if (dr != null)
            {
                EmpName = dr["EmpName"].ToString();
                Birthday = DateTime.Parse(dr["Birthday"].ToString());
                return true;
            }
            else
            {
                EmpName = string.Empty;
                Birthday = null;
                return false;
            }
        }

        private void btnOut_Click(object sender, EventArgs e)
        {
            int EmpNO = 0;
            if (!int.TryParse(txtEmpNO.Text, out EmpNO) || EmpNO < 0) return;

            string EmpName = string.Empty;
            DateTime? Birthday = null;
            if (FuncOut(EmpNO,out EmpName , out Birthday))
            {
                lblMessage.Text = string.Format(string.Format("員工姓名:{0}、生日:{1:D}", EmpName, Birthday));
            }
            else
            {
                lblMessage.Text = "沒有該員工編號";
            }
        }
    }
}
[C#] Function 回傳多值-1

MVA 範例:利用 Struct 回傳多值
namespace MVATwentyQuestions
{
  class Program
  {

    struct MinMax
    {
      public int min;
      public int max;
    }

    static void Main(string[] args)
    {
      int[] myArray = new int[] { 12, 34, 56, 90 };
      MinMax results = MultipleReturns(myArray);
      int arrayMin = results.min;
      int arrayMax = results.max;

      Console.WriteLine("Array min is {0}, and array max is {1}", arrayMin, arrayMax);
    }

    static MinMax MultipleReturns(int[] myArray)
    {

      MinMax values = new MinMax();
      values.min = myArray.Min();
      values.max = myArray.Max();

      return values;
    }
  } 
}
[C#] Function 回傳多值-2

沒有留言:

張貼留言