Skip to main content
 首页 » 编程设计

c#之MatchCollection 类型的集合中项目的基础类型是什么

2024年05月22日41虾米姐

我假设它是 Match 类型,但这不正确,因为我遇到了错误

Cannot implicitely convert type type 'System.Collections.IEnumerator' to type 'System.Collections.Generic.IEnumerator

在线

IEnumerator<Match> friendsULsEnumerator = friendsULs.GetEnumerator(); 

其中 friendsULs 属于 MatchCollection 类型。我试过做

var friendsULsEnumerator = friendsULs.GetEnumerator(); 

并将鼠标悬停在 var 上以查看 Visual Studio 是否告诉我具体类型,但它只显示了 IEnumerable。 :(

为了将我的问题扩展到更大的问题,我试图从 string

中获取 Donald Trump、Hillary Clinton 等的值
<h2>Friends</h2><ul><li>Donald Trump</li><li>Hillary Clinton</li>...</ul> 

在较大的字符串中只出现一次。所以我有的是

                MatchCollection friendsULs = DataReader._fregx.Matches(sr.ReadToEnd()); 
                if ( friendsULs.Count != 1 ) throw new Exception(String.Format("Couldn't find exactly one piece of HTML matching {0}",  
                                                                                DataReader._fregx.ToString())); 
                IEnumerator<Match> friendsULsEnumerator = friendsULs.GetEnumerator(); 
                if ( friendsULsEnumerator.MoveNext() )  { } // because MoveNext() returns a bool, this useless block is necessary 
                MatchCollection friendsLIs = DataReader._lregx.Matches(friendsULsEnumerator.Current.ToString());  

但也许您可以建议一种更紧凑、更优雅的方式来完全做到这一点。

请您参考如下方法:

您正在调用的方法,GetEnumerator是由非泛型 IEnumerable 定义的方法界面。它返回一个非通用的 IEnumerator ,这与 IEnumerator<T> 不同.所以回答你的问题:MatchCollection确实是Match的集合对象,但因为它没有实现通用 IEnumerable<Match>接口(interface),您需要手动“转换”。 OfType方法正是这样做的:转换一个非泛型 IEnumerable集合到指定类型的通用类型。

也就是说,GetEnumerator是您在“规范的 C#”中很少需要的方法。从您的代码示例来看,您似乎只需要获得第一个 Match在集合中。这对于 LINQ 来说更容易也更优雅,例如 Single运算符(operator):

Match match = friendsULs.OfType<Match>().Single();