-1

我尝试在我的事件中返回一个对象:

public class MyEvent : EventArgs
{
 public Channels number = new Channels(); // Channels is a class where i declared only variables( i try to return all variables inside this class)
 public MyEvent(Channels numero)
 {
  return numero;
 }
}

此代码不起作用,我不知道如何返回包含我的 Channels 变量的对象。

4

2 回答 2

4

将其更改为:

public class MyEvent : EventArgs
{
 public Channels Number {get;}

 public MyEvent(Channels numero)
 {
   Number = numero;
   //return numero; You cannot use "return" in a CTOR!
 }
}

然后你可以像这样在 EventHandler 中使用它:

void MyEventHandler( object sender, MyEvent e )
{
   // sender => object that raised the event
   // e => an instance of `MyEvent`, having a property, we can read.
   var channels = e.Number; // use the info
}

当然你会在它被触发之前注册它:

someInstanceProvidingTheEvent.MyEventHappened += MyEventHandler;

引发事件的工作方式如下:

// assume we are in the class that offers the Event
public event EventHandler<MyEvent> MyEventHappened;

protected virtual void OnMyEventHappened( Channels chans )
{
    // You may want to add some error fortification, here
    MyEventHappened?.Invoke(this, new MyEvent(chans));
}

// raise it
public void SomeMethod(){
    var theChannels = new Channels();
    // yadda yadda
    // now it happens!
    OnMyEventHappened(theChannels);
}
于 2020-08-20T08:32:58.247 回答
0
    public class MyEvent : EventArgs
    {
        public Channels _channels { get; set; }

        public MyEvent(Channels numero)
        {
            _channels = numero;
        }
    }
    public class Program
    {
        public Main()
        {
            Channels myChannels = new Channels();
            MyEvent _myEvent = new MyEvent(myChannels);

            var youWant = _myEvent._channels;
        }
    }
于 2020-08-20T08:56:02.777 回答