• 妙用Object


    妙用Object

      当你在写C#程序时,经常会用到“ToString()”这个方法,而且如果你细心你点就会发现所有的引用类型都含有“ToString()”这个方法,那么你知道为什么会这样吗?很简单,因为所有的引用类型都继承自Object这个类,而“ToString”这个方法便是Object的一个成员,所以所有的引用类型都拥有“ToString()”这个成员。接下来,我们将通过几段代码来深入理解Object的作用。

    1.Object的成员:

    方法 返回类型 虚拟 静态 说明
    Object() N/A System.Object类型的构造函数,由派生类的构造函数自动调用
    ~Object()(也称为Finalize()) N/A System.Object类型的析构函数,由派生类的析构函数调用,不能手动调用
    Equals(object) bool 把调用该方法的对象与另一对象相比,如果它们相等,就返回true。默认的实现代码会查看对象参数是否引用了同一个对象。如果想以不同的方式来比较对象,则可以重写该方法,例如,比较两个对象的状态。
    Equals(object,object) bool 这个方法比较传送给它的两个对象,看看它们是否相等。检查时使用了 Equals(object) 方法。注意,如果两个对象都是空引用,这个方法就返回true。
    ReferenceEquals(objcet,object) bool 这个方法比较传送给它的两个对象,看看它们是不是同一个实例的引用。
    ToString() String 返回一个对应于对象实例的字符串。默认情况下,这是一个类类型限定名称,但可以重写它,给类类型提供合适的实现方式。
    MemberwiseClone() object 通过创建一个新对象实例并复制成员,以复制该对象。成员不会得到这些成员的新实例。新对象的任何引用类型成员都将引用与源类型形同的对象,这个方法是受保护的,所以只能在类或派生的类中使用。
    GetType() System.Type 以System.Type对对象的形式返回对象的额类型
    GetHashCode() int 在需要次参数的地方,用作对象的散列函数,它返回一个以压缩形似标识的对象的值

     

    2.object与自定义类型:

     

      所有的类都继承自object类,我们自己写的类同样如此(如果你没有显示的指明基类,编译器会默认为object)。所以我们编写一些类时,可以利用object已经提供的方法。比如我们常用的“ToString”方法,通过重写,可以现实不同的字符串的版本等。object也可用于向上转型与向下转型

     

     

    3.Object在事件处理时的妙用:

      在写事件处理程序时,我们通常会这样写: public void Btn_Click(object sender,EventArgs e){}  ,第一个参数总是 object类型,为什么要这样定义?要弄懂问题,首先要知道这个“sender”所表示的含义:sender指的是调用这个事件处理程序的对象。而这样定义的好处可以通过下面的两段代码来看出:

     

    建立一个winForm窗体应用程序,项目名为Calculate,下面为完整源代码(已测试):

    //项目文件 Calculate.Designer.cs
    namespace Sample_Windows
    {
        partial class Calculate
        {
            /// <summary>
            /// 必需的设计器变量。
            /// </summary>
            private System.ComponentModel.IContainer components = null;
    
            /// <summary>
            /// 清理所有正在使用的资源。
            /// </summary>
            /// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
            protected override void Dispose(bool disposing)
            {
                if (disposing && (components != null))
                {
                    components.Dispose();
                }
                base.Dispose(disposing);
            }
    
            #region Windows 窗体设计器生成的代码
    
            /// <summary>
            /// 设计器支持所需的方法 - 不要
            /// 使用代码编辑器修改此方法的内容。
            /// </summary>
            private void InitializeComponent()
            {
                this.btn9 = new System.Windows.Forms.Button();
                this.btn8 = new System.Windows.Forms.Button();
                this.btn7 = new System.Windows.Forms.Button();
                this.btn6 = new System.Windows.Forms.Button();
                this.btn5 = new System.Windows.Forms.Button();
                this.btn4 = new System.Windows.Forms.Button();
                this.btn3 = new System.Windows.Forms.Button();
                this.btn2 = new System.Windows.Forms.Button();
                this.btn1 = new System.Windows.Forms.Button();
                this.btn0 = new System.Windows.Forms.Button();
                this.btnAdd = new System.Windows.Forms.Button();
                this.btnDiv = new System.Windows.Forms.Button();
                this.btnMul = new System.Windows.Forms.Button();
                this.btnSub = new System.Windows.Forms.Button();
                this.btnClear = new System.Windows.Forms.Button();
                this.resultBox = new System.Windows.Forms.TextBox();
                this.btnResult = new System.Windows.Forms.Button();
                this.SuspendLayout();
                // 
                // btn9
                // 
                this.btn9.Location = new System.Drawing.Point(12, 66);
                this.btn9.Name = "btn9";
                this.btn9.Size = new System.Drawing.Size(40, 31);
                this.btn9.TabIndex = 0;
                this.btn9.Text = "9";
                this.btn9.UseVisualStyleBackColor = true;
                this.btn9.Click += new System.EventHandler(this.btn9_Click);
                // 
                // btn8
                // 
                this.btn8.Location = new System.Drawing.Point(59, 66);
                this.btn8.Name = "btn8";
                this.btn8.Size = new System.Drawing.Size(40, 31);
                this.btn8.TabIndex = 1;
                this.btn8.Text = "8";
                this.btn8.UseVisualStyleBackColor = true;
                this.btn8.Click += new System.EventHandler(this.btn8_Click);
                // 
                // btn7
                // 
                this.btn7.Location = new System.Drawing.Point(105, 66);
                this.btn7.Name = "btn7";
                this.btn7.Size = new System.Drawing.Size(40, 31);
                this.btn7.TabIndex = 2;
                this.btn7.Text = "7";
                this.btn7.UseVisualStyleBackColor = true;
                this.btn7.Click += new System.EventHandler(this.btn7_Click);
                // 
                // btn6
                // 
                this.btn6.Location = new System.Drawing.Point(12, 103);
                this.btn6.Name = "btn6";
                this.btn6.Size = new System.Drawing.Size(40, 31);
                this.btn6.TabIndex = 3;
                this.btn6.Text = "6";
                this.btn6.UseVisualStyleBackColor = true;
                this.btn6.Click += new System.EventHandler(this.btn6_Click);
                // 
                // btn5
                // 
                this.btn5.Location = new System.Drawing.Point(59, 103);
                this.btn5.Name = "btn5";
                this.btn5.Size = new System.Drawing.Size(40, 31);
                this.btn5.TabIndex = 4;
                this.btn5.Text = "5";
                this.btn5.UseVisualStyleBackColor = true;
                this.btn5.Click += new System.EventHandler(this.btn5_Click);
                // 
                // btn4
                // 
                this.btn4.Location = new System.Drawing.Point(105, 103);
                this.btn4.Name = "btn4";
                this.btn4.Size = new System.Drawing.Size(40, 31);
                this.btn4.TabIndex = 5;
                this.btn4.Text = "4";
                this.btn4.UseVisualStyleBackColor = true;
                this.btn4.Click += new System.EventHandler(this.btn4_Click);
                // 
                // btn3
                // 
                this.btn3.Location = new System.Drawing.Point(12, 140);
                this.btn3.Name = "btn3";
                this.btn3.Size = new System.Drawing.Size(40, 31);
                this.btn3.TabIndex = 6;
                this.btn3.Text = "3";
                this.btn3.UseVisualStyleBackColor = true;
                this.btn3.Click += new System.EventHandler(this.btn3_Click);
                // 
                // btn2
                // 
                this.btn2.Location = new System.Drawing.Point(59, 140);
                this.btn2.Name = "btn2";
                this.btn2.Size = new System.Drawing.Size(40, 31);
                this.btn2.TabIndex = 7;
                this.btn2.Text = "2";
                this.btn2.UseVisualStyleBackColor = true;
                this.btn2.Click += new System.EventHandler(this.btn2_Click);
                // 
                // btn1
                // 
                this.btn1.Location = new System.Drawing.Point(105, 140);
                this.btn1.Name = "btn1";
                this.btn1.Size = new System.Drawing.Size(40, 31);
                this.btn1.TabIndex = 8;
                this.btn1.Text = "1";
                this.btn1.UseVisualStyleBackColor = true;
                this.btn1.Click += new System.EventHandler(this.btn1_Click);
                // 
                // btn0
                // 
                this.btn0.Location = new System.Drawing.Point(12, 177);
                this.btn0.Name = "btn0";
                this.btn0.Size = new System.Drawing.Size(40, 31);
                this.btn0.TabIndex = 9;
                this.btn0.Text = "0";
                this.btn0.UseVisualStyleBackColor = true;
                this.btn0.Click += new System.EventHandler(this.btn0_Click);
                // 
                // btnAdd
                // 
                this.btnAdd.Location = new System.Drawing.Point(151, 66);
                this.btnAdd.Name = "btnAdd";
                this.btnAdd.Size = new System.Drawing.Size(40, 31);
                this.btnAdd.TabIndex = 10;
                this.btnAdd.Text = "+";
                this.btnAdd.UseVisualStyleBackColor = true;
                this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click);
                // 
                // btnDiv
                // 
                this.btnDiv.Location = new System.Drawing.Point(151, 103);
                this.btnDiv.Name = "btnDiv";
                this.btnDiv.Size = new System.Drawing.Size(40, 31);
                this.btnDiv.TabIndex = 11;
                this.btnDiv.Text = "-";
                this.btnDiv.UseVisualStyleBackColor = true;
                this.btnDiv.Click += new System.EventHandler(this.btnDiv_Click);
                // 
                // btnMul
                // 
                this.btnMul.Location = new System.Drawing.Point(151, 140);
                this.btnMul.Name = "btnMul";
                this.btnMul.Size = new System.Drawing.Size(40, 31);
                this.btnMul.TabIndex = 12;
                this.btnMul.Text = "*";
                this.btnMul.UseVisualStyleBackColor = true;
                this.btnMul.Click += new System.EventHandler(this.btnMul_Click);
                // 
                // btnSub
                // 
                this.btnSub.Location = new System.Drawing.Point(151, 177);
                this.btnSub.Name = "btnSub";
                this.btnSub.Size = new System.Drawing.Size(40, 31);
                this.btnSub.TabIndex = 13;
                this.btnSub.Text = "/";
                this.btnSub.UseVisualStyleBackColor = true;
                this.btnSub.Click += new System.EventHandler(this.btnSub_Click);
                // 
                // btnClear
                // 
                this.btnClear.Location = new System.Drawing.Point(105, 177);
                this.btnClear.Name = "btnClear";
                this.btnClear.Size = new System.Drawing.Size(40, 31);
                this.btnClear.TabIndex = 14;
                this.btnClear.Text = "C";
                this.btnClear.UseVisualStyleBackColor = true;
                this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
                // 
                // resultBox
                // 
                this.resultBox.Location = new System.Drawing.Point(13, 24);
                this.resultBox.Name = "resultBox";
                this.resultBox.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
                this.resultBox.Size = new System.Drawing.Size(178, 21);
                this.resultBox.TabIndex = 15;
                this.resultBox.Text = "0";
                // 
                // btnResult
                // 
                this.btnResult.Location = new System.Drawing.Point(58, 177);
                this.btnResult.Name = "btnResult";
                this.btnResult.Size = new System.Drawing.Size(40, 31);
                this.btnResult.TabIndex = 16;
                this.btnResult.Text = "=";
                this.btnResult.UseVisualStyleBackColor = true;
                this.btnResult.Click += new System.EventHandler(this.btnResult_Click);
                // 
                // Calculate
                // 
                this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F);
                this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
                this.ClientSize = new System.Drawing.Size(202, 226);
                this.Controls.Add(this.btnResult);
                this.Controls.Add(this.resultBox);
                this.Controls.Add(this.btnClear);
                this.Controls.Add(this.btnSub);
                this.Controls.Add(this.btnMul);
                this.Controls.Add(this.btnDiv);
                this.Controls.Add(this.btnAdd);
                this.Controls.Add(this.btn0);
                this.Controls.Add(this.btn1);
                this.Controls.Add(this.btn2);
                this.Controls.Add(this.btn3);
                this.Controls.Add(this.btn4);
                this.Controls.Add(this.btn5);
                this.Controls.Add(this.btn6);
                this.Controls.Add(this.btn7);
                this.Controls.Add(this.btn8);
                this.Controls.Add(this.btn9);
                this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
                this.Name = "Calculate";
                this.Text = "Calculate";
                this.ResumeLayout(false);
                this.PerformLayout();
    
            }
    
            #endregion
    
            private System.Windows.Forms.Button btn9;
            private System.Windows.Forms.Button btn8;
            private System.Windows.Forms.Button btn7;
            private System.Windows.Forms.Button btn6;
            private System.Windows.Forms.Button btn5;
            private System.Windows.Forms.Button btn4;
            private System.Windows.Forms.Button btn3;
            private System.Windows.Forms.Button btn2;
            private System.Windows.Forms.Button btn1;
            private System.Windows.Forms.Button btn0;
            private System.Windows.Forms.Button btnAdd;
            private System.Windows.Forms.Button btnDiv;
            private System.Windows.Forms.Button btnMul;
            private System.Windows.Forms.Button btnSub;
            private System.Windows.Forms.Button btnClear;
            private System.Windows.Forms.TextBox resultBox;
            private System.Windows.Forms.Button btnResult;
        }
    }
    //项目文件 Calculate.cs
    using System;
    using System.Windows.Forms;
    
    namespace Sample_Windows
    {
        public partial class Calculate : Form
        {
            public Calculate()
            {
                InitializeComponent();
            }
    
            private string _firstNumber = String.Empty;
            private string _secondNumber = String.Empty;
            private string _operation = "+";
    
            private bool _flag = false;
    
            private void btn9_Click(object sender, EventArgs e)
            {
                if (!_flag)
                {
                    _firstNumber += btn9.Text;
              resultBox.Text=_firstNumber; }
    else { _secondNumber += btn9.Text;
             resultBox.Text = secondNumber; }
    } ......
    ......//此处沈略部分代码(btn8_Click,btn7_Click,btn6_Click...)
    ......
         private void btn0_Click(object sender, EventArgs e) { if (!_flag) { _firstNumber += btn0.Text;
             resultBox.Text=_firstNumber; }
    else { _secondNumber += btn0.Text;
             resultBox.Text=_secondNumber; }
    } private void btnResult_Click(object sender, EventArgs e) { if (_firstNumber != String.Empty && _secondNumber != String.Empty) { double a = Convert.ToDouble(_firstNumber); double b = Convert.ToDouble(_secondNumber); switch (_operation) { case "+": resultBox.Text = Convert.ToString(a + b); break; case "-": resultBox.Text = Convert.ToString(a - b); break; case "*": resultBox.Text = Convert.ToString(a*b); break; case "/": resultBox.Text = Convert.ToString(a/b); break; } } else { MessageBox.Show("Error!!!","Warning",MessageBoxButtons.OK,MessageBoxIcon.Warning); } } private void btnClear_Click(object sender, EventArgs e) { resultBox.Text = "0"; _flag = false; } private void btnAdd_Click(object sender, EventArgs e) { _operation = "+"; resultBox.Text = _operation; _flag = !_flag; } private void btnDiv_Click(object sender, EventArgs e) { _operation = "-"; resultBox.Text = _operation; _flag = !_flag; } private void btnMul_Click(object sender, EventArgs e) { _operation = "*"; resultBox.Text = _operation; _flag = !_flag; } private void btnSub_Click(object sender, EventArgs e) { _operation = "/"; resultBox.Text = _operation; _flag = !_flag; } } }

    这是一个简单的计算器程序,在上面的代码中,共有16个事件处理程序,而其中10个数字处理程序与4个操作符处理程。看以看出代码很长,修改修改起来也很麻烦。接下来看一下下面的代码:

    //项目文件 Calculate.Designer.cs
    ...
    this.btn0.Click += new System.EventHandler(this.btn_Click);this.btn2.Click += new System.EventHandler(this.btn_Click);
    this.btn3.Click += new System.EventHandler(this.btn_Click);
    this.btn4.Click += new System.EventHandler(this.btn_Click);
    this.btn5.Click += new System.EventHandler(this.btn_Click);
    ...
    this.btnSub.Click += new System.EventHandler(this.btnOperation_Click);
    
    ...
    
    
    
    //项目文件 Calculate.cs
    using System;
    using System.Windows.Forms;
    
    namespace Sample_Windows
    {
        public partial class Calculate : Form
        {
            public Calculate()
            {
                InitializeComponent();
            }
    
            private string _firstNumber = String.Empty;
            private string _secondNumber = String.Empty;
            private string _operation = "+";
    
            private bool _flag = false;
    
            private void btn_Click(object sender, EventArgs e)
            {
                Button btn = (Button) sender;   //获取触发此事件处理程序的Button对象
                if (!_flag)
                {
                    _firstNumber += btn.Text;
                     resultBox.Text = _firstNumber;
               }
                else
                {
                    _secondNumber += btn.Text;
                    resultBox.Text = _secondNumber;
                }
            }
    
            private void btnResult_Click(object sender, EventArgs e)
            {
                if (_firstNumber != String.Empty && _secondNumber != String.Empty)
                {
                    double a = Convert.ToDouble(_firstNumber);
                    double b = Convert.ToDouble(_secondNumber);
                    _firstNumber = String.Empty;
                    _secondNumber = String.Empty;
    
                    switch (_operation)
                    {
                        case "+":
                            resultBox.Text = Convert.ToString(a + b);
                            break;
                        case "-":
                            resultBox.Text = Convert.ToString(a - b);
                            break;
                        case "*":
                            resultBox.Text = Convert.ToString(a*b);
                            break;
                        case "/":
                            resultBox.Text = Convert.ToString(a/b);
                            break;
                    }
                }
                else
                {
                    MessageBox.Show("Error!!!","Warning",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                }
            }
    
            private void btnOperation_Click(object sender, EventArgs e)
            {
                Button btn = (Button) sender;   //获取触发此事件处理程序的Button对象
                _operation = btn.Text;
                resultBox.Text = _operation;
                _flag = !_flag;
            }
    
            private void btnClear_Click(object sender, EventArgs e)
            {
                _flag = false;
                resultBox.Text = "0";
    
            }
        }
    }

     这段代码与上面要实现的功能完全一样,但只有4个时间处理程序,一个数字处理程序与一个字符处理程序,很明显,代码明显的精简的不少,而且修改起来也更加方便。从上面的例子可以看出使用object与不使用object有多么大的不同。

    总结:

    (1)在写事件处理程序时,可以将事件处理程序按事件的属性分类(如上面例子中的数字处理,操作处理,计算处理),再通过object这个类来实现用一个事件处理程序处理同一类事件。这样既避免了代码的重复,又增加了可读性和易维护性!

    (2)object可以实现控件之间的交互,因为所有类都继承自object,所以通过多态性,可以将控件与object的引用绑定,以便于在不同的方法间传递,再通过向下转型解绑,就可以轻松实现控件之间的交互。

  • 相关阅读:
    Qt 信号与槽
    Qt 项目中main主函数及其作用
    Windows下的GUI 库
    ABP进阶教程0
    ABP入门教程15
    ABP入门教程13
    ABP入门教程12
    ABP入门教程11
    ABP入门教程10
    ABP入门教程9
  • 原文地址:https://www.cnblogs.com/SilentCode/p/4865489.html
Copyright © 2020-2023  润新知