關於“委託”

最近一直在加班,現在工作的效率是越來越低,現在也沒有時間來這裏轉了。

“委託”這是在.Net中提出一個概念。這個概念是隻有在最近使用VB.Net時纔剛剛接觸(現在的概念太多了,一天一個,追不上了,就懶得追了,等待着剩下的那個了!:<),現在覺得這個東東還挺好用,先寫一些現在的使用心得。

 我在這個項目之前一直對VB沒有什麼好感,這個印象是在VB 6.0時期留下的,一直到現在。微軟在推出.Net後,將原來的VB進行了大面積的改動,向其中增加了很多新的概念,使它成爲了一個真正意義上的面向對象的語言了。在VB.Net中包含了這些語言之後,它的表達能力大大提高,但是它的運行效率還沒有提高。

前面說了很多的費話,現在進入我們今天的正題——“委託”。“委託是一種數據結構,它引用靜態方法或引用類實例及該類的實例方法。”這個是MSDN中關於委託的定義。這說明在.net中引入“委託”概念的目的,它的概念與C++中的函數指針一致,但在使用上,“委託”要更加靈活。下面是MSDN中關於委託的一段例程。

 

Public Class SamplesDelegate

   
' Declares a delegate for a method that takes in an int and returns a String.
   Delegate Function myMethodDelegate(myInt As IntegerAs [String]

   
' Defines some methods to which the delegate can point.
   Public Class mySampleClass

      
' Defines an instance method.
      Public Function myStringMethod() 'myStringMethod

      
' Defines a static method.
      Public Shared Function mySignMethod(myInt As IntegerAs [String]
         
If myInt > 0 Then
            
Return "+"
         
End If
         
If myInt < 0 Then
            
Return "-"
         
End If
         
Return ""
      
End Function
 'mySignMethod
   End Class
 'mySampleClass

   
Public Shared Sub Main()

      
' Creates one delegate for each method.
      Dim mySC As New mySampleClass()
      
Dim myD1 As New myMethodDelegate(AddressOf mySC.myStringMethod)
      
Dim myD2 As New myMethodDelegate(AddressOf mySampleClass.mySignMethod)

      
' Invokes the delegates.
      Console.WriteLine("{0} is {1}; use the sign ""{2}""."5, myD1(5), myD2(5))
      Console.WriteLine(
"{0} is {1}; use the sign ""{2}""."- 3, myD1(- 3), myD2(- 3))
      Console.WriteLine(
"{0} is {1}; use the sign ""{2}""."0, myD1(0), myD2(0))

   
End Sub
 'Main

End Class
 'SamplesDelegate

Delegat Function myMethodDelegate(myInt As IntegerAs [String]  '定義一個委託

這個委託的參數是一個Integer型。

委託在使用方面和普通函數一樣,它還可用異步激發,它的這種調用方式要比C++中函數指針更靈活、更方便。

本文是在同事(師傅)討論之後的一些心得。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章