海技术人员,
在 C# 中,我们如何定义接受 DateTime 对象并返回 bool 值的多播委托(delegate)。
谢谢
最佳答案
public delegate bool Foo(DateTime timestamp);
这是使用您描述的签名声明委托(delegate)的方法。所有委托(delegate)都可能是多播的,它们只需要初始化。如:
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<bool> returnValues = new List<bool>();
foreach(Foo f in fAll.GetInvocationList())
{
returnValues.Add(f(timestamp));
}
关于C#:创建具有 bool 返回类型的多播委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1356488/