如何访问自定义EventArgs类的按钮点击事件?自定义、按钮、事件、EventArgs

2023-09-03 07:19:48 作者:玩世不恭的男人

作为后续行动: 在自定义EventArgs类 访问值

As a follow up to: access values within custom eventargs class

如何访问中自定义EventArgs类公共变量,用按一下按钮或任何其他方法?

How do I access public variables within custom Eventargs class, using button click or any other method?

示例自定义事件参数类:

Example Custom Event Args class:

public class TraderEventArgs: EventArgs
{
    private int _shares;
    private string _symbol;

    public TraderEventArgs(int shs, string sym)
    {
        this._shares = shs;
        this._symbol = sym;
    } 

    public decimal Price 
    {
        get {return _prices;}       
    }

   public int Shares
   {
       get { return _shares; }
   }
}

button_click事件背后code:

Code behind button_click event:

public partial class _Default : System.Web.UI.Page
{
    protected void Button1_Click(object sender, EventArgs e)
    {
        // run trader app
        myApp.Main();

        // try to access TraderEventArgs class
        TraderEventArgs: EventArgs ev = TraderEventArgs: EventArgs();   // Invalid

        TraderEventArgs ev = new TraderEventArgs();   // this needs argument variables that are unassigned... ?

        TraderEventArgs ev = (TraderEventArgs)e;  //  Unable to cast object of type 'System.EventArgs' to type TraderEventArgs'.

        string sym = ev.Symbol.ToString();
        string sharws = ev.Shares.ToString();

        // do something with data

     }

感谢您的帮助。

thanks for help.

推荐答案

在按钮单击事件引发的,它创造了 EventArgs的,获取传递到E。该对象不是由你创造的,而是由框架,并且是类型 EventArgs的。这prevents您无法将其转换为不同的类型。

When the button click event is raised, it's creating the EventArgs that gets passed into "e". That object was not created by you, but rather by the framework itself, and is of type EventArgs. This prevents you from being able to cast it to a different type.

如果你想有一个引发事件 TraderEventArgs ,你需要创建一个事件,$ P $型pferably 事件处理程序< TraderEventArgs> ,而引发此事件的地方,是在你的控制。这样您就可以直接生成的类正确的类型,然后处理它(在一个单独的事件处理程序)。

If you want to have an event that raises TraderEventArgs, you need to create an event, preferably of type EventHandler<TraderEventArgs>, and raise this event somewhere that is in your control. This allows you to generate the class of the correct type, then handle it (in a separate event handler) directly.