簡體   English   中英

將包含添加到現有功能 <T, object> 屬性

[英]Add Contains to existing Func<T, object> property

我正在嘗試為現有的Func屬性列表創建Contains子句,但是我不知道如何將其附加到先前傳遞的屬性列表中。

public static List<Func<T, bool>> GetPropertyWhereClauses<T>(List<Func<T, object>> properties, string queryPhrase)
    {
        var whereClauses = new List<Func<T, bool>>();

        foreach (var property in properties)
        {
            /// how to add Contains to existing property Func<T, object> ?
            whereClauses.Add(property.Contains(queryPhrase));
        }

        return whereClauses;
    }

如何添加呢? 我嘗試使用一些Expression.Call,但它沒有將Func作為參數。

如果僅要將每個Func<T, object>轉換為Func<T, bool>如果第一個轉換為string的func返回對象包含queryPhrase,則可以執行以下操作:

public static List<Func<T, bool>> GetPropertyWhereClauses<T>(List<Func<T, object>> funcs, string queryPhrase)
{
    var whereClauses = new List<Func<T, bool>>();
    foreach (var func in funcs)
    {
        whereClauses.Add(o => func(o).ToString().Contains(queryPhrase));
    }
    return whereClauses;
}

或更適合LINQ:

 public static List<Func<T, bool>> GetPropertyWhereClauses<T>(List<Func<T, object>> funcs, string queryPhrase)
{
    return funcs.Select(func => new Func<T, bool>(o => func(o).ToString().Contains(queryPhrase)).ToList();
}

如果reutrn對象實際上是列表而不是字符串,則可以通過類似的方式檢查queryPhrase是否是列表的一部分:

public static List<Func<T, bool>> GetPropertyWhereClauses<T>(List<Func<T, object>> funcs, string queryPhrase)
{
    return funcs.Select(func => new Func<T, bool>(o => ((List<string>)func(o)).Contains(queryPhrase)).ToList();
}

如果您可以將func返回tpye變成一個對象,這不是最好的主意,則可以將其更改為期望的真實類型,這樣可以節省所有多余的轉換。

鑄造功能<t>功能<object><div id="text_translate"><p>我試圖弄清楚如何將Func&lt;T&gt;傳遞給Func&lt;object&gt;方法參數:</p><pre> public void Foo&lt;T&gt;(Func&lt;T&gt; p) where T: class { Foo(p); } public void Foo(Func&lt;object&gt; p) { }</pre><p> <strong>奇怪的是,它適用於 NET 4.0 Class 庫,但不適用於 Silverlight 4 Class 庫。</strong> 實際上我希望它在 Silverlight 中工作,並且我輸入了諸如Func&lt;T, bool&gt;之類的參數</p></div></object></t>

[英]Casting Func<T> to Func<object>

暫無
暫無

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

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