我能扩展方法添加到列表<>? [重复]

问题描述 投票:-2回答:2

这个问题已经在这里有一个答案:

我有这样的代码:

public static List<Phrase> selectedPhrases;

if  (!App.selectedPhrases.Any(x => x.Viewed == false))
                return;

有没有办法,我可以改变我宣布selectedPhrases的方式,这样我可以做到这样,去年检查任何方式:

if  (App.selectedPhrases.AllViewed())
    return;

我听说扩展方法,但是是可以创建一个列表就像在我的代码?

c#
2个回答
3
投票

您可以在列表编写扩展方法,为你的榜样,短语

public static class Extension
{
    public static bool AllViewed(this List<Phrase> source)
    {
        return source.All(x=>x.Viewed)
    }
}

顺便说一句,你并不需要检查!Any(x=>c.Viewed==false),存在使用。所有()扩展方法选择如图上面的代码

你可以阅读更多的扩展方法here的语法。

您可能也有兴趣,就如何LINQ的扩展方法是通过看一些源代码at referencesource的实现阅读。


1
投票

您可以创建一个静态类扩展方法:

public static class PhraseExtensions
{
    public static bool AllViewed(this List<Phrase> phrases)
    {
        return !phrases.Any(p => !p.Viewed);
        // phrases.All(p => p.Viewed); would be better suited.
    }
}

在这里看到关于扩展的文档:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods

© www.soinside.com 2019 - 2024. All rights reserved.