创建委托事件
我正在尝试创建一个可以以其他forms访问的委托事件。 但主要forms没有看到能够看到我的代表。 它说代理名称此时无效。 模态forms
public partial class GameOverDialog : Window { public delegate void ExitChosenEvent(); public delegate void RestartChosenEvent(); public GameOverDialog() { InitializeComponent(); } private void closeAppButton_Click(object sender, RoutedEventArgs e) { ExitChosenEvent exitChosen = Close; exitChosen(); Close(); } private void newGameButton_Click(object sender, RoutedEventArgs e) { RestartChosenEvent restart = Close; restart(); Close(); } }
主要forms:
private void ShowGameOver(string text) { var dialog = new GameOverDialog { tb1 = { Text = text } }; dialog.RestartChosenEvent += StartNewGame(); dialog.Show(); } private void StartNewGame() { InitializeComponent(); InitializeGame(); }
在@Fuex的帮助之后 *
private void ShowGameOver(string text) { var dialog = new GameOverDialog { tb1 = { Text = text } }; dialog.RestartEvent += StartNewGame; dialog.ExitEvent += Close; dialog.Show(); }
它不起作用,因为delegate void RestartChosenEvent()
声明了允许封装方法的引用类型。 所以通过使用它+= StartNewGame
给出一个错误。 正确的代码是:
public partial class GameOverDialog : Window { delegate void myDelegate(); public myDelegate RestartChosenEvent; public myDelegate ExitChosenEvent; public GameOverDialog() { InitializeComponent(); } private void closeAppButton_Click(object sender, RoutedEventArgs e) { ExitChosenEvent(); this.Close(); } private void newGameButton_Click(object sender, RoutedEventArgs e) { RestartChosenEvent(); this.Close(); } }
然后在你的主窗体中你必须使用StartNewGame
,它是要传递的方法的指针,而不是StartNewGame()
:
private void ShowGameOver(string text) { var dialog = new GameOverDialog { tb1 = { Text = text } }; dialog.RestartChosenEvent += StartNewGame; dialog.Show(); }
“委托名称此时无效”错误也可能在您定义委托而不使用new
关键字时发生。 例如:
// In asp.net the below would typically appear in a parent page (aspx.cs page) that // consumes a delegate event from a usercontrol: protected override void OnInit(EventArgs e) { Client1.EditClientEvent += Forms_Client.EditClientDelegate(Client1_EditClientEvent); //NOTE: the above line causes 'delegate name is not valid at this point' error because of the lack of the 'new' keyword. Client1.EditClientEvent += new Forms_Client.EditClientDelegate(Client1_EditClientEvent); //NOTE: the above line is the correct syntax (no delegate errors appear) }
要将其置于上下文中,您可以在下面看到委托的定义。 在asp.net中,如果您正在定义需要从其父页面(托管控件的页面)获取值的usercontrol,那么您将在usercontrol中定义您的委托,如下所示:
//this is the usercontrol (ascx.cs page): public delegate void EditClientDelegate(string num); public event EditClientDelegate EditClientEvent; //call the delegate somewhere in your usercontrol: protected void Page_Load(object sender, System.EventArgs e) { if (EditClientEvent != null) { EditClientEvent("I am raised"); } }