C#:Creating Multicast delegate with boolean return type

前端 未结 5 1704
执念已碎
执念已碎 2020-12-08 17:24

Hai Techies,

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

Thanks

5条回答
  •  广开言路
    2020-12-08 17:29

    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;
    

    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 returnValues = new List();
    foreach(Foo f in fAll.GetInvocationList())
    {
        returnValues.Add(f(timestamp));
    }
    

提交回复
热议问题