开发者

Problem with Predicates in C#

I have the following method definition (EDITED to remove redundant generic):

public static T SearchAgaistValues<T>(Dictio开发者_运维知识库nary<string, string> input, 
string key, List<T> values, Predicate<T> match, out string[] cmdParams)

My simplified requirements are as follows. I need to search input for key, and if found, see if its value appears in values. However, values is generic (and will obviously contain a string that I need to match). Therefore, the way I see it, I have to pass a predicate method to perform the matching.

However, every example of Predicate<T> I have seen has a hard coded comparitor. I need to compare the found key's value to each item in values. I cannot pass these values, however.

I can't see how to do this outside of a foreach loop with a delegate based match method.

Am I missing something here?


As I see it you have two options, without changing crazy requirements.

Option 1 is to use Func<string, T1, bool> instead of Predicate<T1>. This way the predicate can convert between string and T1 as needed and return the boolean matched result.

public static T1 SearchAgaistValues<T, T1>(
            Dictionary<string, string> input, 
            string key, 
            List<T1> values, 
            Func<string, T1, bool> match, 
            out string[] cmdParams)

Alternatively you can pass an additional Converter<T1, string> parameter to convert the looked-up string to a T1 and then compare using the predicate.

public static T1 SearchAgaistValues<T, T1>(
            Dictionary<string, string> input, 
            string key, 
            List<T1> values, 
            Converter<T1, string> converter,
            Predicate<T1> match, 
            out string[] cmdParams)

Both cases are less than ideal though. This function sounds a lot more like a problem looking for a solution than the other way around. The signature is a bit crazy and seems like it can be greatly simplified by restating the requirements or breaking it up into pieces.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜