星期一, 3月 09, 2015

[C#] Event 練習

利用最低薪資(假設是 20,000)來練習建立 class 的 event

[C#] Event 練習-1


HR project Employ class
namespace HR
{
    public class Employ
    {
        private int _Salary;
        public int Salary
        {
            get { return this._Salary; }
            set 
                {
                    if (value > 20000)
                    {
                        this._Salary = value;
                    }
                    else
                    {
                        SalaryErrorEventArgs e = new SalaryErrorEventArgs();
                        e.ErrorSalary = value;
                        e.ErrorMessage = string.Format("{0} 低於最低薪資",value);
                        OnSalaryError(e);
                    }
                }
        }

        // Step3:建立 Event - SalaryError Event 並使用 delegate - SalaryEventHandler
        public event SalaryErrorEventHandler SalaryError;
        // Step4:建立觸發 Event 的 Method - OnSalaryError
        protected virtual void OnSalaryError(SalaryErrorEventArgs args)
        {
            if (SalaryError != null)
            {
                SalaryError(this,args);
            }
        }
    }

    // Step1:定義 EventArgs 物件規格,繼承 System.EventArgs(.NET 4.0 開始就沒有強迫一定要繼承 EventArgs class 了)
    public class SalaryErrorEventArgs:EventArgs
    {
        public int ErrorSalary { get; set; }
        public string ErrorMessage { get; set; }
   
        #region 建構式
        public SalaryErrorEventArgs()
        {
            ErrorSalary = 0;
            ErrorMessage = "";
        }

        public SalaryErrorEventArgs(int salary, string message)
        {
            ErrorSalary = salary;
            ErrorMessage = message;
        } 
        #endregion
    }

    // Step2: 建立 Delegate 
    public delegate void SalaryErrorEventHandler(object sender,SalaryErrorEventArgs e);
}
Salary peoject 的測試網站
  • TextBox (txtSalary)讓使用者輸入薪資
  • Button (btnRun)執行
  • label (lblErrorMessage)顯示錯誤訊息
using HR;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnRun_Click(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(txtSalary.Text)) return;

        Employ emp = new Employ();
        emp.SalaryError += emp_SalaryError;
        emp.Salary = Convert.ToInt32(txtSalary.Text);
    }

    void emp_SalaryError(object sender, SalaryErrorEventArgs e)
    {
        lblErrorMessage.Text = e.ErrorMessage;
    }
}
[C#] Event 練習-2

沒有留言:

張貼留言