请教大牛们
public event SerialDataReceivedEventHandler DataReceived;
和
public SerialDataReceivedEventHandler DataReceived;
的区别.Public Event
public event SerialDataReceivedEventHandler DataReceived;
和
public SerialDataReceivedEventHandler DataReceived;
的区别.Public Event
MyClass mc=new MyClass();
mc.DataReceived+=MyClass_DataReceived;public void MyClass_DataReceived()
{}
不加event的话,mc.后没有DataReceived,你咋弄?
using System.Linq;namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
var x = new TA();
x.Alert = process1;
x.Alert += process2;
x.Alert += process3;
x.callMethod();
Console.WriteLine("-----------------------");
var m = (MulticastDelegate)x.Alert;
x.Alert = (TA.EvtHandler)Delegate.Combine(m.GetInvocationList().Where((p, i) => i % 2 == 0).ToArray()); //只留下奇数个回调
x.callMethod();
Console.WriteLine("-----------------------");
x.Alert = process3; //彻底重建回调
x.callMethod();
Console.ReadKey();
} private static void process1()
{
Console.WriteLine("process1");
} private static void process2()
{
Console.WriteLine("process2");
} private static void process3()
{
Console.WriteLine("process3");
} } public class TA
{
public delegate void EvtHandler(); public EvtHandler Alert; public void callMethod()
{
if (Alert != null)
Alert();
}
}
}
你可以看到,在类型TA之外可以随便摧毁 x.Alert 的定义。也许你认为这很“灵活”。但是要知道这不是事件的初衷。我们之所以要使用“事件”来进行设计,就是因为它是安全的,保证不会被各种随意插入的调用x对象的代码按照它自己的想法去相互冲突地去操作x.Alert。
我试了下,结合sp1234的代码,我错了。C#可以智能地视为多播委托。