대리자에 문제가 있으며을 참조하고 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
.
이벤트를 사용하려면 먼저 호출하기 전에 먼저 값을 지정해야합니다. 이는 할당 및 호출의 인덱스가 잘못되었음을 의미합니다. 다음과 같아야합니다.
MandarComp += CambiarTexto;//For event, += is used more offen than directly assignment.
MandarComp(Componente);
작동합니다.
또한 최신 버전의 C #을 사용 MandarComp?.Invoke()
하는 경우 NullReferenceExcption을 피하기 위해 다음과 같이 작성할 수 있습니다 .
또한 델리게이트 및 이벤트의 기본적인 사용부터 시작하는 것이 좋습니다. 대리인이 소유자 클래스에서 사용되는 경우 이는 낭비입니다. 해당 메서드를 직접 호출하면 동일한 작업이 수행됩니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다