我有一个具有两个属性的类: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
答案 0 :(得分:0)
您的代码包含以下关键行...
C.Weigh = Convert.ToDecimal(textBox1.Text);
C.Id = TxtId.Text;
请注意,在Id
之后设置了Weigh
。因此,在设置Weigh
的时候,它将在下一行设置Id
之前引发一个与Id
中的值有关的事件。
交换两行,以便首先设置Id
,您的代码将按预期运行。