在C#中,Jon Skeet指出:
开发人员经常混淆事件和委托实例,或者用委托类型声明的事件和字段。
在阅读了他的解释之后,我了解了更多,尽管我仍然对事件的确切含义感到困惑。从下面的代码看来,一个事件所做的一切似乎是限制一个类必须委派另一个类中的字段的访问。
...您通常不希望类外的代码能够随意更改(或调用)事件的处理程序... [所以]编译器将声明转换为具有默认添加/删除实现的事件和相同类型的私有字段。
换句话说,由于访问控制,事件不同于委托。还是仅仅因为乔恩所说的“类似领域的事件”?
换句话说,C#是否同时支持事件和类似字段的事件,或者这两种说法是相同的?
此处的代码示例https://dotnetfiddle.net/7fOwvb
using System;
using System.Reflection;
public delegate void TheDelegate(string message);
public static class Program
{
public static event TheDelegate TheEvent;
public static TheDelegate DelInstance;
public static void Main()
{
DelInstance = new TheDelegate(TheMethod);
DelInstance += TheMethod;
DelInstance.Invoke("Invoke the delegate.");
PrintMemberInfo(DelInstance.GetType());
TheEvent += TheMethod;
TheEvent += TheMethod;
TheEvent.Invoke("Invoke the event.");
PrintMemberInfo(TheEvent.GetType());
new AnotherClass();
}
// Create a method for a delegate.
public static void TheMethod(string message)
{
Console.WriteLine(message);
}
public static void PrintMemberInfo(System.Type t)
{
foreach (MemberInfo m in t.GetMembers())
{
Console.Write(m.Name + ", ");
}
Console.WriteLine("\n");
}
}
public class AnotherClass
{
public AnotherClass()
{
Program.DelInstance += new TheDelegate(AnotherMethod);
Program.DelInstance.Invoke("Another class");
// Error... we can only call += or -+
// Program.TheEvent.Invoke();
}
public void AnotherMethod(string message)
{
Console.WriteLine(message);
}
}
类字段事件是等同于自动属性的事件,即具有编译器生成add
/remove
访问器的事件。
类田间活动
在包含事件声明的类或结构的程序文本中,某些事件可以像字段一样使用。要以这种方式使用,事件不得为抽象事件或外部事件,并且不得显式包含event-accessor-declaration。这样的事件可以在允许字段的任何上下文中使用。该字段包含一个委托(§15),该委托引用已添加到事件的事件处理程序的列表。如果未添加事件处理程序,则该字段包含null。
(C#5.0规范)
您可以在C#中使用自定义访问器(add
和remove
)实现事件。
event EventHandler IDrawingObject.OnDraw
{
add
{
...
}
remove
{
...
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句