标签:ext2 一个 star 定义 simple 引用 name bsp str
定义事件前必须先定义用于该事件的委托类型
public delegate void simDelegate(string Name);
定义了委托后,就可以把事件本身定义为一个类成员
public class SimpleEve { public event simDelegate simEve;
订阅方法,前提是方法的参数必须与事件的委托类型的参数相一致
simEve += simpleTest.Texts;
simEve += simpleTest.Text2;
引发事件,必须在该类中引发,在外部只能订阅,引发时要注意是否有参数
simEve(name);
整体代码:
public delegate void simDelegate(string Name); public class SimpleEve { public event simDelegate simEve; private string name; public SimpleEve(string newName) => this.name = newName; public void Start()=> simEve(name);//引发事件 } public class SimpleTest { public void Texts(string name) => Console.WriteLine($"6666{name}"); public void Text2(string name) => Console.WriteLine($"{name}6666"); }
static void Main(string[] args) { SimpleEve simpleEve = new SimpleEve("TT"); SimpleTest simpleTest = new SimpleTest(); simpleEve.simEve += simpleTest.Texts; simpleEve.simEve += simpleTest.Text2; simpleEve.Start(); Console.ReadKey(); }
class DelegateTest { public event EventHandler eventTest; //创建多用途事件 private EventArgsTest eventArgsTest; public DelegateTest() { eventArgsTest = new EventArgsTest("TT"); eventTest += new EventHandler(StrTest.Run); } public void Start() => eventTest(this, eventArgsTest); //引发事件 } class StrTest {public static void Run(object source, EventArgs e) //委托参数 { string test = $"asfsfagsg sa {((EventArgsTest)e).Message} sad "; //多态性 Console.Write(test); } }
class EventArgsTest:EventArgs { private string message; public string Message { get => message; } public EventArgsTest() => message = "no message"; public EventArgsTest(string newMessage) => message = newMessage; }
DelegateTest delegateTest = new DelegateTest(); delegateTest.Start();
多用途事件有两个参数:
object source ------ 引发事件的对象的引用
ElapsedEventArgs e ------- 由事件传送的参数
source是指定生成事件的对象
EventArgs为参数
标签:ext2 一个 star 定义 simple 引用 name bsp str
原文地址:https://www.cnblogs.com/xt112233/p/10199987.html