C 高階程式設計 第8版 委託宣告 使用(第一節)

2022-03-22 14:18:41 字數 1569 閱讀 2596

首先,宣告乙個currency的結構。currency結構有自己的tostring()過載方法和乙個與getcurrencyunit()的簽名相同的靜態方法。這樣,就可以用同乙個委託變數呼叫這些方法了:

struct currency

public override string tostring()

.", dollars, cents);

}public static string getcurrencyunit()

public static explicit operator currency(float value)

}public static implicit operator float(currency value)

public static implicit operator currency(uint value)

public static implicit operator uint(currency value)

}

下面就是getstring例項,**如下:

private delegate string getastring();

static void main()

", firststringmethod());

currency balance = new currency(34, 50);

// firststringmethod references an instance method

firststringmethod = balance.tostring;

console.writeline("string is ", firststringmethod());

// firststringmethod references a static method

firststringmethod = new getastring(currency.getcurrencyunit);

console.writeline("string is ", firststringmethod());

}

這段**說明了如何通過委託呼叫方法,然後重新給委託指定在類的不同例項上的引用的不同方法,甚至可以指定靜態方法,或者在類的不同型別的例項上引用的方法。只要每個方法的簽名匹配委託定義即可。

執行上面的程式,會得到委託引用的不同方法的輸出結果:

string is 40

string is $34.50

string is dollar

但是,我們實際上還沒有說明把乙個委託傳遞給另外乙個方法的具體過程,也沒有得到任何特別有用的結果。呼叫int和currency物件的tostring()的方法要比使用委託直觀的多!!! 但是,需要用乙個相當複雜的的示例來說明委託的本質,才能真正領悟到委託的用處。等到下一節,書中就會給出兩個委託的示例。第乙個示例僅使用委託呼叫兩個不同的操作。他說明了如何把委託傳遞給方法,如何使用委託陣列,但是這仍然沒有很好的說明:沒有委託,就不能完成很多任務作。第二個示例就複雜得多了,它有乙個類bubblesorter,這個類實現了乙個方法,按照公升序排列乙個物件陣列。沒有委託是很難編寫出這個類的!!!(詳見下一節)

C 高階程式設計(第9版) 第06章 陣列

好久沒發東西了 一停下來就會變懶。雖然沒完成,也就是它吧 以下正文 本章要點 1 簡單陣列 2 多維陣列 3 鋸齒陣列 4 array類 5 作為引數的陣列 6 列舉 7 元組 8 結構比較 同一型別和不同型別的多個物件 如果需要使用同一型別的多個物件,就可以使用集合 參見第10章 和陣列。c 用特...

C 程式設計 第2版 課後習題答案 第8章

1.使用結構體變數來表示學生資料 姓名 學號和3門課程的成績。從鍵盤輸入個學生的資料,要求列印出每個學生的姓名和3門課程的平均成績,此外要求按學生的平均成績降序輸出,按學生姓名搜尋。view code 1 include 2 include 3 using namespace std 4struct...

C 6 0高階程式設計(第10版)C 基礎

string是不可變的引用型別,改變變數值時,並不會替換原來的值,在堆上會為新值分配乙個新物件。允許在字串字面量中包含換行符 允許把花括號放在包含乙個變數甚至 表示式的字串中,變數或 表示式的結果放在字串中花括號所在的位置 string s1 a string writeline s1 is 可空型...