簡體   English   中英

SmartEnumerable和Regex.Matches

[英]SmartEnumerable and Regex.Matches

我想使用Jon Skeet的SmartEnumerable循環一個Regex.Matches但它不起作用。

foreach (var entry in Regex.Matches("one :two", @"(?<!\w):(\w+)").AsSmartEnumerable())

有人可以解釋一下為什么嗎? 並提出一個解決方案,使其工作。 謝謝。

錯誤是:

'System.Text.RegularExpressions.MatchCollection' does not contain a definition
for 'AsSmartEnumerable' and no extension method 'AsSmartEnumerable' accepting
a first argument of type 'System.Text.RegularExpressions.MatchCollection' could
be found (are you missing a using directive or an assembly reference?)

編輯:我想你忘了在示例代碼中插入.AsSmartEnumerable()調用。 不編譯的原因是因為所述延伸法僅適用於IEnumerable<T>而不是非通用上IEnumerable接口。


並不是說你不能用這種方式枚舉比賽; 只是因為MatchCollection類沒有實現通用IEnumerable<T>接口,只有IEnumerable接口,因此entry類型將被推斷為object

如果你想堅持使用隱式類型,你必須生成一個IEnumerable<T>來幫助編譯器:

foreach (var entry in Regex.Matches("one :two", @"(?<!\w):(\w+)").Cast<Match>())
{ 
   ...
} 

或者,使用顯式輸入的更好方式(編譯器為您插入一個強制轉換):

foreach (Match entry in Regex.Matches("one :two", @"(?<!\w):(\w+)"))
{ 
   ...
} 

生成智能可枚舉的最簡單方法是使用提供的擴展方法:

var smartEnumerable = Regex.Matches("one :two", @"(?<!\w):(\w+)")
                           .Cast<Match>()
                           .AsSmartEnumerable();

foreach(var smartEntry in smartEnumerable)
{
   ...
}

這將需要using MiscUtil.Collections.Extensions; 源文件中的指令。

暫無
暫無

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

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