繁体   English   中英

C# 返回带有事件的 object

[英]C# Return an object with an event

我尝试在我的活动中返回 object:

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 变量的 object。

将其更改为:

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);
}
    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;
        }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM