在 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 = "沒有該員工編號";
}
}
}
}