【问题标题】:How to pass predicate to function in C#?如何将谓词传递给 C# 中的函数?
【发布时间】:2012-05-10 08:59:18
【问题描述】:

我有:

 public void InitializeStatusList(DropDownList list)
    {
       var dictionaryEntries = GetEntriesFromDatabase();
       list.DataSource = dictionaryEntries.Where(entry => entry is EntryStatus1 || entry is EntryStatus2);
       list.DataBind();           
    }

我有很多这样的功能。我想编写带有dictionaryEntries 查询条件作为谓词传递的通用函数。

例如:

public void InitializeStatusList(DropDownList list)
{
    CommonInitializeStatusList(DropDownList list, entry => entry is EntryStatus1 || entry is EntryStatus2);
}

public void CommonInitializeStatusList(DropDownList list, ??????????????? predicate)
{                       
    var dictionaryEntries = GetEntriesFromDatabase();
    list.DataSource = dictionaryEntries.Where(predicate);
    list.DataBind();        
}

??????????????? 代表什么

提前致谢

【问题讨论】:

  • 感谢@reinierpost,我刚刚修正了initialize 错字。

标签: c# asp.net c#-4.0 predicate


【解决方案1】:

Func<Entry, bool> predicate 应该可以工作,其中Entryentry 变量的类型。

【讨论】:

  • 这个 Entry 类要包含的命名空间/库是什么?
  • @thanatorr - 条目是自定义枚举。
  • @MichałKuliński 是的,我现在想通了,谢谢!
【解决方案2】:

你可以这样做:

public void InitializeStatusList(DropDownList list)
{    
    Func<Entry,bool> predicate=entry=>entry is EntryStatus1 || entry is EntryStatus2;
    CommonInitializeStatusList(list, predicate);
}

public void CommonInitializeStatusList(DropDownList list, Func<Entry,bool> predicate)
{                                 
    var dictionaryEntries = GetEntriesFromDatabase();    
    list.DataSource = dictionaryEntries.Where(predicate);
    list.DataBind();

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-13
    • 2018-08-19
    相关资源
    最近更新 更多