[英]C# Noob - Passing a condition as a parameter
我已經有解決此問題的方法,但對我來說似乎很混亂且不切實際。
我打算做的是逐行讀取文件(由於文件大小,一次將其全部加載到內存中是不切實際的),如果滿足某些條件(例如:該行與regex模式匹配,或包含某些關鍵字,或等於某些字符串)
這是我理想的狀態:
void TryGetLineIf(string filePath, Condition condition, out string desiredLine)
{
StreamReader fileReader = new StreamReader(filePath);
string currentLine = "";
while (!fileReader.EndOfStream)
{
currentLine = fileReader.ReadLine();
if (condition)
{
desiredLine = currentLine;
}
}
}
但是,我不知道該如何處理condition參數。 我能想到的唯一出路是用枚舉替換條件(LineSelectionOptions.IsRegexMatch,LineSelectionOptions.ContainsString ...),向void添加一個額外的參數,並在可能的值之間進行切換。 如果相關的話,我正在使用.NET 2.0。
如果您知道函數將具有的參數,則可以使用Func傳遞一個函數,該函數將返回布爾值
您的方法定義將如下所示
void TryGetLineIf(string filePath, Func<string, bool> condition, out string desiredLine)
如果行將是這樣
if(condition(currentLine)) {
desiredLine = currentLine;
}
對該方法的調用將是這樣的
Func<string, bool> condition = (line) => line.Length > 1;
string desiredLine;
TryGetLineIf("C:\\....file.pdf", condition, out desiredLine)
但是,因為您在2.0中工作,所以您可能希望使用委托來模擬Func。請參見此方法。 如何在.NET Framework 2.0中模擬“ Func <(Of <(TResult>)>)委托”? 或使用代理C#替換此Func
請原諒格式,因為我在用手機。
無論如何,我認為這是使用yield return
理想選擇,因為調用者可以決定break
,而不希望在任何行之后讀取文件的其余部分。 這將允許。 另外,調用者可以執行鏈接並進行進一步處理。 此外,不需要out
參數。
確保使用using
語句,如果在.NET 2.0中可用,請改用File.ReadLines
方法:它逐行讀取並且更加簡單。 到家后,我將嘗試用我提出的建議修改答案。
public static IEnumerable<string> TryGetLineIf(string filePath, Condition condition
{
StreamReader fileReader = new StreamReader(filePath);
string currentLine = "";
while (!fileReader.EndOfStream)
{
currentLine = fileReader.ReadLine();
if (condition.MeetsCriteria(currentLine))
{
yield return currentLine;
}
}
}
最后要注意的是,如果您將委托作為條件而不是另一個答案中建議的類實例,則將更健壯。
@Gonzalo。-感謝您的回答,我設法在少數情況下使用了它。 但是現在當我嘗試在Func委托中使用更多參數來執行此操作時出現問題,例如,當嘗試檢查行是否匹配某個Regex模式時:
Func<string, string, bool> condition =
(line, pattern) => new Regex(pattern).IsMatch(line)
IEnumerable<string> LinesIWant =
ReturnLineIf("C:\test.txt", condition);
這是方法:
IEnumerable<string> ReturnLineIf(string filePath, Func<string, string, bool> condition)
{
// (snip)
// How do I specify a pattern when calling the method?
if (condition(currentLine, "This should be the pattern..."))
{
yield return currentLine;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.