我有这个代码:
public static List<Phrase> selectedPhrases;
Run Code Online (Sandbox Code Playgroud)
和
if (!App.selectedPhrases.Any(x => x.Viewed == false))
return;
Run Code Online (Sandbox Code Playgroud)
有什么方法可以改变我声明 selectedPhrases 的方式,以便我可以以这种方式进行最后一次检查:
if (App.selectedPhrases.AllViewed())
return;
Run Code Online (Sandbox Code Playgroud)
我听说过扩展方法,但是可以像在我的代码中那样为 List 创建一个方法吗?
您可以在 List 上编写扩展方法,例如,Phrase
public static class Extension
{
public static bool AllViewed(this List<Phrase> source)
{
return source.All(x=>x.Viewed)
}
}
Run Code Online (Sandbox Code Playgroud)
顺便说一句,你不需要检查 !Any(x=>c.Viewed==false),可以选择使用 .All() 扩展方法,如上面的代码所示
您可能还有兴趣通过查看referencesource 中的一些源代码来了解 Linq 扩展方法是如何实现的。