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

C#:使用布尔返回类型创建多播委托,c#,delegates,C#,Delegates,海科技 在C#中,如何定义接受DateTime对象并返回布尔值的多播委托 谢谢任何代理都可以是多播代理 class Test { public delegate bool Sample(DateTime dt); static void Main() { Sample j = A; j += B; j(DateTime.Now); } static bool A(DateTime d) {

海科技

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


谢谢

任何代理都可以是多播代理

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;
    }
}
delegate bool myDel(DateTime s);
myDel s = someFunc;
s += someOtherFunc;

委托对象的一个有用属性 它们可以分配给一个 要多播的委托实例 使用+运算符。沉着的 代理调用这两个代理 由…组成。仅代表 可以组合相同的类型

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

这里有一个关于

这是如何声明具有您描述的签名的委托。所有委托都可能是多播的,它们只需要初始化。例如:

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;

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

代理上有两种方法

  • 开始觉醒
  • EndInvoke
该链接使用代码示例详细描述了这些内容


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

在您的例子中,不是自己创建委托

最好在C#中使用预定义的委托,例如Func谓词

public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
public委托TResult Func(T1 arg1,T2 arg2);

公共委托布尔谓词(T obj);

调用组合委托时,该委托的返回值会发生什么变化?是否有某种数组允许您在调用返回值后检查它们?我以前使用过多播委托,但从未想过它们具有返回类型。
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;
List<bool> returnValues = new List<bool>();
foreach(Foo f in fAll.GetInvocationList())
{
    returnValues.Add(f(timestamp));
}
public delegate TResult Func<in T1, in T2, out TResult>(T1 arg1, T2 arg2);
public delegate bool Predicate<in T>(T obj);