Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
650 views
in Technique[技术] by (71.8m points)

c# - Default value on generic predicate as argument

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,

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...