泛型$ P $ pdicate作为参数的默认值 [英] Default value on generic predicate as argument
问题描述
我第一次的问题:)
我需要一些方法使用一个通用的格式来定义默认predicate
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:
有关'predicate默认参数值必须是一个编译时常
Default parameter value for 'predicate' must be a compile-time constant
是否有这样做,我很想念还是应该一做predicate功能可空,并相应地改变我的功能逻辑的顺利地?
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) {
// ...
}
此外,还有一个特定的 predicate&LT; T&GT;
在mscorlib中的委托,您可以使用来代替。这是相同的签名 Func键&LT; T,BOOL&GT;
,但它明确地标记为它决定是否对 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
这篇关于泛型$ P $ pdicate作为参数的默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!