C# - 传递函数以将对象属性派生为参数

Nei*_*eil 1 c# linq generics

我想通过在函数参数中指定我搜索的Foo的属性来使这个函数更通用.目前,我必须为Foo的每个属性提供一个函数,而不仅仅是一个泛型函数.

private Func<Foo, bool> ByName(bool _exclude, string[] _searchTerms)
{
    if (_exclude)
    {
        return x => !_searchTerms.Contains( x.Name.Replace(" ", "").ToLower() );
    }

    return x => _searchTerms.Contains( x.Name.Replace(" ", "").ToLower() );
}
Run Code Online (Sandbox Code Playgroud)

是否可以使此函数更通用,以便能够传递Foo的搜索属性?

Dan*_*rth 6

您可以轻松添加Func<Foo, string>:

private Func<Foo, bool> By(Func<Foo, string> property,
                           bool exclude, string[] searchTerms)
{
    if (exclude)
    {
        return x => !searchTerms.Contains( property(x).Replace(" ", "").ToLower() );
    }

    return x => searchTerms.Contains( property(x).Replace(" ", "").ToLower() );
}
Run Code Online (Sandbox Code Playgroud)

你会这样称呼它:

By(x => x.Name, ...);
Run Code Online (Sandbox Code Playgroud)

请注意,此方法不通用.它只支持类型的属性string,因为您的搜索方法Replace在属性上使用,而您searchTerms也是strings.

顺便说一句:请注意我命名参数的方式..NET命名约定不对参数使用下划线.