delegate vs. event (多谢Cavingdeep兄的指正,等待更新……)
{
public delegate void TestDelegate(
string s);
public interface ITest {
// 【区别】 1. event可以用在interface中,而plain delegate不可以(因为它是field)
event TestDelegate TestE;
// Passed
TestDelegate TestD;
// Error: Interfaces cannot contain fields
}
public class Parent {
public event TestDelegate TestE;
public TestDelegate TestD;
protected void RaiseTestE(
string s)
{
TestE(s);
// The event 'EventAndDelegate.Parent.TestE' can only
// be used from within the type 'EventAndDelegate.Parent'
}
}
public class Child : Parent {
void ChildFunc()
{
// 【区别】 2. event不允许在声明它的class之外(即使是子类)被调用(除此之外只能用于+=或-=),而plain delegate则允许
TestD("OK");
// Passed
TestE("Failure");
// Error: The event 'EventAndDelegate.Parent.TestE' can only appear on
// the left hand side of += or -= (except when used from within
// the type 'EventAndDelegate.Parent')
// 【补充】 在子类中要触发父类声明的event,通常的做法是在父类中声明一个protected的Raisexxx方法供子类调用
RaiseTestE("OK");
// The class 'EventAndDelegate.Child' can only call the
// 'EventAndDelegate.ParentRaiseTestE' method to raise the event
// 'EventAndDelegate.Parent.TestE'
// 【区别】 同2#
object o1 = TestD.Target;
object o2 = TestE.Target;
// The class 'EventAndDelegate.Child' can only call the
// 'EventAndDelegate.ParentRaiseTestE' method to raise the event
// 'EventAndDelegate.Parent.TestE'
// 【区别】 同2#
TestD.DynamicInvoke("OK");
TestE.DynamicInvoke("OK");
// The class 'EventAndDelegate.Child' can only call the
// 'EventAndDelegate.ParentRaiseTestE' method to raise the event
// 'EventAndDelegate.Parent.TestE'
}
}
class Other
{
static void Main(
string[] args)
{
Parent p =
new Parent();
p.TestD +=
new TestDelegate(p_Test1);
// Passed
p.TestE +=
new TestDelegate(p_Test1);
// Passed
// 【区别】 3. event不允许使用赋值运算符,而plain delegate则允许。
// 注意,对plain delegate,使用赋值运算符意味着进行了一次替换操作!
p.TestD =
new TestDelegate(p_Test2);
// Passed
p.TestE =
new TestDelegate(p_Test2);
// Error: The event 'EventAndDelegate.Parent.TestE' can only appear on
// the left hand side of += or -= (except when used from within
// the type 'EventAndDelegate.Parent')
// 【区别】 同2#
p.TestD("OK");
// Passed
p.TestE("Failure");
// Error: The event 'EventAndDelegate.Parent.TestE' can only appear on
// the left hand side of += or -= (except when used from within
// the type 'EventAndDelegate.Parent')
}
static void p_Test1(
string s)
{
Console.WriteLine("p_Test1: " + s);
}
static void p_Test2(
string s)
{
Console.WriteLine("p_Test2: " + s);
}
}
}
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。