C#控件事件处理代码的复用

复用前:

        private void nudSMBegin_MouseUp(object sender, MouseEventArgs e)
        {
            nudSMBegin.Select(0, nudSMBegin.Value.ToString().Length);
        }

        private void nudSMEnd_MouseUp(object sender, MouseEventArgs e)
        {
            nudSMEnd.Select(0, nudSMEnd.Value.ToString().Length);
        }

……

多个NumericUpDown具有相似代码,这种情况下可以把这此相似的代码重构成一个函数,方法如下:

复用后:

        private void nudSMBegin_MouseUp(object sender, MouseEventArgs e)
        {
            nudSM_MouseUp(sender,e);
        }

        private void nudSMEnd_MouseUp(object sender, MouseEventArgs e)
        {
            nudSM_MouseUp(sender, e);
        }

        private void nudSM_MouseUp(object sender, MouseEventArgs e)
        {
            System.Windows.Forms.NumericUpDown myNud = (System.Windows.Forms.NumericUpDown)sender;
            myNud.Select(0, myNud.Value.ToString().Length);
        }

你可能感兴趣的:(object,C#)