2011-05-25 79 views
0

正如我的代碼建議,我試圖創建一個委託,它將指向StringBuff方法BuffString,它會創建一個StringBuilder,它將有相當數量的設置等。C#代表和事件邏輯和語法問題

我的問題是,由於某種原因,不管它是什麼,我嘗試我無法將我在Sprite類中所做的StringBuff類的引用傳遞給委託的構造函數而不會收到錯誤。在此基礎上,我覺得創建一個事件可能對幫助啓動代表很有幫助。

主要問題是,我現在剛剛掌握了這兩個概念,以及如何將它們用作其他編程語言允許的函數指針替換。

如果任何人有任何想法,我需要做什麼來做到這一點,我一定會很感激。

下面的代碼:

public class StringBuff 
     { 
      private static StringBuilder stringBuffer = new StringBuilder(); 

      public static StringBuilder BuffString(string _string) //--may possibly have to use IntPtr to reference stringBuffer here. 
      //This is the equivalent to the "strbuff_new" C++ method variant, designed to update the stringBuffer. 
      { 
       int iCounter = 0; 

       stringBuffer.Append(_string + " "); 

       iCounter += _string.Length + 1; 

       if (iCounter == stringBuffer.Capacity - 1) 
       { 
        stringBuffer.Capacity += stringBuffer.Capacity; 
       } 

       return stringBuffer; 
      } 
     } 

     public delegate void UpdateStringBuffer(StringBuff sender); 

     public class Sprite : SpriteInterface.ISprite 
     { 
      private StringBuff stringBuff = new StringBuff(); 

      public event UpdateStringBuffer stringBuffEvent 
      { 
       add 
       { 
        Console.WriteLine("Adding"); 
        stringBuffEvent += value; 
       } 
       remove 
       { 
        Console.WriteLine("Removing..."); 
        stringBuffEvent -= value; 
       } 
      } 

      static void Main() 
      { 
       new Sprite().stringBuffEvent += new UpdateStringBuffer(stringBuff); 
      } 




     } 
+0

請發表你的錯誤,也是如此。 – alexD 2011-05-25 05:29:32

回答

1

你是誤會了使用事件和委託。

當你想將事件處理程序添加到一個事件,你傳遞同類型的委託作爲事件(你做了正確的)
但是當你創建一個代表,你應該在構造函數傳遞什麼(大部分時間)是方法名稱而不是一些變量,因爲委託是一種指向(列表)函數的指針。

我建議你閱讀更多關於代表Akram Shahda的建議,但現在我會告訴你,你應該傳遞給委託構造函數的方法應該有相同的簽名 - 意味着返回相同的值並且接受相同的參數。因此,例如,你可以有:

// This method have the same signature as UpdateStringBufferDelegate 
public void SomeMethod (StringBuff buff) 
{ 
    // Doing somthing here 
} 

然後你就可以在做你的主:

// Passing method's name and not a variable!! 
new Sprite().stringBuffEvent += new UpdateStringBuffer(SomeMethod); 

將被傳遞給函數本身(一些StringBuff)只在當時所確定的實際工作參數對事件的調用。
你應該閱讀更多關於這一點。

祝你好運!

0

你做錯了,

new Sprite().stringBuffEvent += new UpdateStringBuffer(stringBuff); 

上面的代碼是無效的,由於以下原因。

1.您的UpdateStringBuffer所採用的stringBuff是Sprite中的一個StringBuff實例。

2。您正在從靜態Main方法訪問stringBuff,該方法對stringBuff所在的位置沒有任何想法。

0

- 委託的構造函數只能有一個參數Method。防爆

public delegate void UpdateStringBuffer(StringBuff sender); 

- 你可以聲明烏爾事件,並添加烏爾Splite類中定義的方法烏爾的方法。例如:

public event UpdateStringBuffer stringBuffEvent; 

public ProcessUpdateStringBuffer(UpdateStringBuffer yourMethod) 
{ 
     stringBuffEvent += yourMethod 
} 

- 從烏拉圭回合的主U可以定義烏爾法的事件並調用它像這樣:

Sprite sprite = new Sprite(); 
sprite.ProcessUpdateStringBuffer(UpdateStringBuffer(urMethod)); 
sprite.stringBuffEvent(ur parameters);