我正在尝试创建一个可以其他形式访问的委托事件。但主要形式似乎没有能够看到我的代表。它表示委托名称此时无效。 模态形式
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();
}
}
主要形式:
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();
}
答案 0 :(得分:4)
它不起作用,因为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();
}
答案 1 :(得分:1)
'委托名称此时无效'错误也可能在您定义委托而不使用 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");
}
}