[英]c#, .net, delegate, asynchronous callback. What am I doing wrong here?
這是游戲菜單中按鈕的一個小類。
我希望能夠在實例化每個按鈕時傳遞委托方法_triggerMethod。 然后,當該按鈕實例觸發方法被調用時,該委托方法將被調用。
我在這里第一次嘗試使用C#進行委托。 就我在這里解釋文檔而言,我正在做的事情應該可以工作,但是Visual Studio在Trigger方法中給了我一個編譯錯誤。
根據msdn的文章,調用委托的代碼不需要了解參數等的原始方法。 我究竟做錯了什么? 同樣在msdn文章中,他們只鍵入“ Del”,這對我不起作用。 我必須輸入“ Delegate”,這很奇怪。
class MenuItem
{
private Rectangle clickArea;
private string displayText;
private Vector2 _position;
private Delegate _triggerMethod;
public MenuItem(Vector2 pos,string txt,Delegate trig)
{
displayText = txt;
_position = pos;
_triggerMethod = trig;
}
public void Draw(SpriteBatch sb)
{
}
public void Select()
{
}
public void DeSelect()
{
}
public void IsMouseOnMe()
{
}
public void Trigger()
{
_triggerMethod();
}
}
您尚未創建任何委托定義。
示例(從您鏈接的MSDN頁面):
public delegate void Del(string message);
然后,您需要使用它作為您的類型:
** snip **
private Del _triggerMethod;
public MenuItem(Vector2 pos,string txt,Del trig)
{
displayText = txt;
_position = pos;
_triggerMethod = trig;
}
** snip **
public void Trigger()
{
_triggerMethod("some message");
}
您可以傳遞委托的引用而無需實際知道期望的參數(因為它只是一個普通引用),但是當您要調用它時,確實需要為其提供正確的參數。
如果要使用Del
類型,則需要定義它:
public delegate void Del(string message);
public class MenuItem
{
private Del _triggerMethod;
public void Trigger()
{
_triggerMethod("Message");
}
}
請注意,您可以使用內置的Action<string>
委托類型,而不用定義自己的委托類型:
Action<string> _triggerMethod;
_triggerMethod("Message");
如果僅使用Delegate
類型,則可以使用DynamicInvoke
調用它:
public void Trigger()
{
_triggerMethod.DynamicInvoke();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.