Default value on generic predicate as argument

后端 未结 3 2044
旧巷少年郎
旧巷少年郎 2020-12-18 18:20

First time question for me :)

I need some way to define a default predicate using a generic on the format

Func

and

相关标签:
3条回答
  • 2020-12-18 18:54

    Try this:

    public bool Broadcast(byte command, MemoryStream data, bool async, Func<T, bool> predicate = default(Func<T, bool>))
    

    But I think you have to check for predicate!=null.

    0 讨论(0)
  • 2020-12-18 18:59

    Default values for method parameters have to be compile-time constants, as the default values are actually copied to all the call sites of the method by the compiler.

    You have to use an overload to do this:

    public bool Broadcast(byte command, MemoryStream data, bool async) {
        return Broadcast(command, data, async, t => true);
    }
    
    public bool Broadcast(byte command, MemoryStream data, bool async, Func<T, bool> predicate) {
        // ...
    }
    

    Also, there is a specific Predicate<T> delegate in mscorlib which you can use instead. It's the same signature as Func<T, bool>, but it explicitly marks it as a delegate which decides whether an action is performed on instances of T

    0 讨论(0)
  • 2020-12-18 19:01

    Make an overload for Broadcast which does not take the last argument.

    0 讨论(0)
提交回复
热议问题