Default value on generic predicate as argument

拥有回忆 提交于 2019-12-01 13:46:15

问题


First time question for me :)

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?

Thanks,


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/4804536/default-value-on-generic-predicate-as-argument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!