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

C#:Creating Multicast delegate with boolean return type(C#:使用布尔返回类型创建多播委托)
本文介绍了C#:使用布尔返回类型创建多播委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

海技术,

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

in C#, how can we define the multicast delegate which accepts a DateTime object and return a boolean.

谢谢

推荐答案

public delegate bool Foo(DateTime timestamp);

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

This is how to declare a delegate with the signature you describe. All delegates are potentially multicast, they simply require initialization. Such as:

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().

Calling fAll, in this case would call both IsGreaterThanNow() and IsLessThanNow().

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

What this doesn't do is give you access to each return value. All you get is the last value returned. If you want to retrieve each and every value, you'll have to handle the multicasting manually like so:

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

这篇关于C#:使用布尔返回类型创建多播委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)