【发布时间】:2020-05-29 07:29:06
【问题描述】:
我对引用 null 的代表有疑问,我有这个问题:
首先我定义要执行的委托:
public delegate void MandarComponente(int Componente);
public event MandarComponente MandarComp;
由于我希望这是在拖放操作中,所以我将放置一些重要的东西的拖放代码
private void Capacitor_MouseDown(object sender, System.Windows.Forms.MouseEventArgs e) //This is a PictureBox Event
{
componente = 1;
Capacitor.DoDragDrop(Capacitor.Image, DragDropEffects.Copy | DragDropEffects.Move);
}
一旦我有了它,我就会在活动中使用它
public void tableLayoutPanel2_DragDrop(object sender, DragEventArgs e)
{
Point pl = new Point(this.Location.X + tableLayoutPanel2.Location.X + 10, this.Location.Y + tableLayoutPanel2.Location.Y + 32);
int R = (int)((e.Y - pl.Y) / pictureBox1.Height);
int C = (int)((e.X - pl.X) / pictureBox1.Width);
Console.WriteLine("X=" + e.X + "Y=" + e.Y + " [" + C + ", " + R + "]");
if (R == tableLayoutPanel2.RowCount) R--;
if (C == tableLayoutPanel2.ColumnCount) C--;
PictureBox pictureBox = (PictureBox)tableLayoutPanel2.GetControlFromPosition(C, R);
if (R == 0 && C == 0 || R == 2 && C == 0 || R == 2 && C == 2 || R == 0 && C == 2)
{
MessageBox.Show("¡No puedes poner un componente ahí!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
pictureBox = null;
}
if (componente == 1 && pictureBox != null)
{
pictureBox.Image = Capacitor.Image;
MandarComp(componente);
MandarComp = new MandarComponente(CambiarTexto);
if (R == 1 && C == 2 || R == 1 && C == 0)
{
pictureBox.Image.RotateFlip(RotateFlipType.Rotate90FlipNone);
}
}
就是引用这个方法:
void CambiarTexto(int Componente)
{
if(Componente==1)
{
label5.Text = "Componente Seleccionado: CAPACITOR";
}
}
但是MandarCom(Componente)的部分总是有NullReferenceException的例外。
编辑:基本上我要做的是委托MandarComponente(int Componente) 保存componente,然后将其发送到CambiarTexto 方法,这样它就会在label5.Text 中执行操作。
【问题讨论】:
-
欢迎来到 Stack Overflow。 “但 MandarCom(Componente) 的部分始终显示 NullReferenceException 异常” - 然后
MandarComp为空。你还没有解释为什么你期望它不为空。 (也不清楚为什么你在调用它之后将它设置在行中 - 这对于一个事件来说是非常不寻常的。) -
@JonSkeet 我是事件处理程序和代表的新手,所以我想做的是创建一个可以将
componente发送到事件CambiarTexto的代表,因此来自标签已更改 -
好的,我认为最好阅读有关事件和代表的教程。通常你会想要一些subscribing事件(你不会在你自己的类中设置它)。
MandarComp(componente)将调用所有现有的事件订阅者——但你没有。我建议你从docs.microsoft.com/en-us/dotnet/standard/events开始 -
@JonSkeet 谢谢,实际上我刚刚看到委托用于链接程序外部的代码;所以基本上我用错了;但是我找不到更好的方法来做到这一点,这是我想到的第一件事。但是谢谢,真的,我要去观看有关事件以及如何处理它们的教程!
-
如果你只是想打电话给
CambiarTexto,那就去做吧:CambiarTexto(componente);。这就是您进行方法调用所需的全部内容。无需委托或事件。