C#:使用布尔返回类型创建多播委托

Hai Techies,

在C#中,我们如何定义接受DateTime对象并返回布尔值的多播委托。

谢谢

public delegate bool Foo(DateTime timestamp); 

这是如何使用您描述的签名声明委托。 所有代表都可能是多播的,他们只需要初始化。 如:

 public bool IsGreaterThanNow(DateTime timestamp) { return DateTime.Now < timestamp; } public bool IsLessThanNow(DateTime timestamp) { return DateTime.Now > timestamp; } Foo f1 = IsGreaterThanNow; Foo f2 = IsLessThanNow; Foo fAll = f1 + f2; 

调用fAll ,在这种情况下将同时调用IsGreaterThanNow()IsLessThanNow()

这不做的是让您访问每个返回值。 你得到的只是返回的最后一个值。 如果要检索每个值,则必须手动处理多播,如下所示:

 List returnValues = new List(); foreach(Foo f in fAll.GetInvocationList()) { returnValues.Add(f(timestamp)); } 

任何委托都可以是多播委托

 delegate bool myDel(DateTime s); myDel s = someFunc; s += someOtherFunc; 

MSDN

委托对象的一个​​有用属性是可以使用+运算符将它们分配给一个委托实例以进行多播。 组合委托调用它组成的两个委托。 只能组成相同类型的代理。

编辑: delagate有一个方法GetInvocationList ,它返回一个带有附加方法的列表。

以下是有关委托调用的参考

 foreach(myDel d in s.GetInvocationList()) { d(); } 
 class Test { public delegate bool Sample(DateTime dt); static void Main() { Sample j = A; j += B; j(DateTime.Now); } static bool A(DateTime d) { Console.WriteLine(d); return true; } static bool B(DateTime d) { Console.WriteLine(d); return true; } } 

我绊倒了同样的问题。 我搜索并在msdn中找到了这个。

http://msdn.microsoft.com/en-us/library/2e08f6yc(v=VS.100).aspx

代表有两种方法

  • 的BeginInvoke
  • EndInvoke会

该链接详细描述了这些代码示例。

我们可以挂钩这些方法来处理委托的返回值。