簡體   English   中英

函數上的自定義EventArgs消息框不顯示發送方類的屬性

[英]Custom EventArgs Messagebox on Function does not show property from sender class

我有一個具有兩個屬性的類:weight和Id。 設置體重后,我想觸發一個事件。 要觸發的事件是一個顯示Id屬性的messageBox。 顯示了消息框,但不包含Id屬性。

這是完整的代碼: https : //pastebin.com/zpHn48gL

public class MyClass
{        
    //Custom type Event declaration
    public event EventHandler<Mas4TEventArgs> Info;
    decimal _weigh;
    //properties
    public string Id { get; set; }
    public decimal Weigh
    {
        get { return this._weigh; }
        set                         //When this property is changed, invoke Info Event, passing Id property to be shown on messagebox.
        {
            this._weigh= value;
            Info?.Invoke(this, new Mas4TEventArgs(this.Id));                
        }
    }    
}

public class Mas4TEventArgs : EventArgs
{        
    //constructor
    public Mas4TEventArgs(string pId) { IdArgu = pId; }        
    //property IdArgu                                          
    public string IdArgu { get; set; }
}

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {

        MyClass C = new MyClass();
        //suscription
        C.Info += C_Info;                                 

        //Function to be triggered by the event
        void C_Info(object sendr, Mas4TEventArgs ev)
        {
            try
            {      //ev.IdArgu doesn't show on the messagebox.                                         
                MessageBox.Show("Evento consumido. " + " Id: " + ev.IdArgu);
            }
            catch (Exception) { }
        }

        //properties
        C.Weigh = Convert.ToDecimal(textBox1.Text);
        C.Id = TxtId.Text;
        //just to check the two properties have been parsed correctly.This works as intended.
        MessageBox.Show("Ingresado: Peso: " + C.Peso.ToString() + " Id: " + C.Id);
    }
}

或者,如果您喜歡這樣: https : //lpaste.net/3710707699130826752

您的代碼包括以下關鍵行...

C.Weigh = Convert.ToDecimal(textBox1.Text);
C.Id = TxtId.Text;

請注意, Id是在Weigh 之后設置的。 因此,在設置了Weigh值的時候,它將在您在下一行設置Id之前引發與Id Id有關的事件。

交換兩行,以便首先設置Id ,您的代碼將按預期運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM