簡體   English   中英

C# 中的謂詞問題

[英]Problem with Predicates in C#

我有以下方法定義(編輯刪除多余的泛型):

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

我的簡化要求如下。 我需要搜索keyinput ,如果找到,看看它的值是否出現在values中。 但是, values是通用的(顯然會包含我需要匹配的字符串)。 因此,在我看來,我必須通過一個謂詞方法來執行匹配。

但是,我見過的每個Predicate<T>示例都有一個硬編碼的比較器。 我需要將找到key's值與values中的每個項目進行比較。 但是,我無法傳遞這些值。

我看不到如何使用基於委托的匹配方法在 foreach 循環之外執行此操作。

我在這里錯過了什么嗎?

在我看來,您有兩種選擇,而無需改變瘋狂的要求。

選項 1 是使用Func<string, T1, bool>而不是Predicate<T1> 這樣謂詞可以根據需要在字符串和 T1 之間進行轉換,並返回 boolean 匹配的結果。

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

或者,您可以傳遞額外的Converter<T1, string>參數以將查找的字符串轉換為 T1,然后使用謂詞進行比較。

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)

不過,這兩種情況都不太理想。 這個 function 聽起來更像是一個尋找解決方案的問題,而不是相反的問題。 簽名有點瘋狂,似乎可以通過重述需求或將其分解為多個部分來大大簡化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM