妙用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的引用綁定,以便於在不同的方法間傳遞,再通過向下轉型解綁,就可以輕松實現控件之間的交互。