泛型谓词的默认值作为参数 [英] Default value on generic predicate as argument
问题描述
我第一次提问:)
我需要一些方法来使用格式上的泛型定义默认谓词
I need some way to define a default predicate using a generic on the format
Func<T, bool>
然后将其用作默认参数.像这样:
and then use this as a default argument. Something like this:
public bool Broadcast(byte command, MemoryStream data, bool async, Func<T, bool> predicate = (T t) => true)
当我这样做时,我收到编译错误:
When i do this i get the compile error:
谓词"的默认参数值必须是编译时常量
Default parameter value for 'predicate' must be a compile-time constant
是否有一种流畅的方法可以做到这一点,我是否应该将谓词函数设为可空并相应地更改我的函数逻辑?
Is there a smooth way of doing this that I am missing or should a make the predicate function nullable and change my function logic accordingly?
谢谢,
推荐答案
方法参数的默认值必须是编译时常量,因为默认值实际上是由编译器复制到方法的所有调用点.
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) {
// ...
}
此外,在 mscorlib 中有一个特定的 Predicate
委托,您可以使用它来代替.它与 Func
的签名相同,但它明确地将其标记为一个委托,该委托决定是否对 T
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
这篇关于泛型谓词的默认值作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!