【问题标题】:Is it possible to delay the "bool" test in a Dictionary<string, Func<bool, object>>是否可以延迟 Dictionary<string, Func<bool, object>> 中的“bool”测试
【发布时间】:2017-02-24 19:47:17
【问题描述】:

我有一个Dictionary&lt;string, Func&lt;bool, object&gt;&gt; 我想有条件地循环遍历字典并仅在bool == true 时添加“对象”。
但我不确定如何将pair.Value() 作为布尔值传递。

foreach (KeyValuePair<string, Func<bool, object>> pair in parameters)
{   
    //error pair.Value(), Delegate Func has 1 parameter(s) but is invoked with 0 arguments.  
    //pair.Value(true) obviously works, but defeats the purpose

    if (pair.Value() != null)
            cmd.Parameters.AddWithValue(pair.Key, pair.Value());
    } 
}

我应该使用Expression&lt;Func&lt;bool, object&gt;&gt; 并编译/评估布尔值吗?如果有,怎么做?

【问题讨论】:

  • 确切地展示了如何在您的问题中向代表传递一个布尔值,所以很明显您确实知道该怎么做。
  • 您的要求有点令人困惑。如果某事属实,您是否尝试添加对象的条目,
  • Func&lt;bool, object&gt; 中没有bool:它表示一个以布尔值作为输入的函数
  • 是的,我想在 pair.Value(bool) 表达式中评估该 bool。这有意义吗?
  • @Robert4Real 不,评估它作为参数接受的布尔值是没有意义的。在您提供布尔值之前没有布尔值,这意味着您必须已经从委托以外的某个来源对其进行了评估。你从评估委托中得到的是object,而不是bool

标签: c# dictionary lambda expression expression-trees


【解决方案1】:

我知道你想存储一个条件,稍后你去拉它时会解决这个条件,所以你真正需要的是这种字典

Dictionary<string, Func<object>> dictionary= new Dictionary<string, Func<object>>()

你会添加这样的条目

dictionary.Add("key", () => /*Insert your condition here*/ 3 == 2 ? /*If True*/ obj : /*If False*/ null );

然后你的代码就完美运行了

foreach (KeyValuePair<string, Func<object>> pair in dictionary)
{     
    if (pair.Value() != null)
    cmd.Parameters.AddWithValue(pair.Key, pair.Value());
}

编辑

很好,那么这里有 2 个选项:

选项 1

你制作了这个字典

var dictionary = new Dictionary<string, Action<bool>>();

然后你像这样添加

dictionary.Add("key", condition => { if (condition) cmd.Parameters.AddWithValue("key", obj); });

现在你的逻辑变成了这个

foreach (KeyValuePair<string, Action<bool>> pair in dictionary)
            pair.Value(bool);

选项 2

看起来你真正想要的是这个

var list = new List<Action<bool>>();
list.Add(condition => { if (condition) cmd.Parameters.AddWithValue("key", obj) });

然后你的逻辑会是这样的

list.ForEach(x => x(bool));

【讨论】:

  • 差不多。理想情况下,我希望将一个 bool 参数传递给函数。因此,与其称它为 If (pair.Value() != null),我更愿意称它为“if (pair.Value(bool))”,而不需要对 NULL 进行测试。
  • 我真正想要的是一个 3 维字典,类似于 Dictionary 如果 bool == true,那么 AddWithValue(pair.Key, pair.Value)。但是这样的东西不存在,除非我使用 TUPLES。
  • 我赞成你提供一个深思熟虑的解释,不像这个线程上的其他一些无用的 cmets。但是,这不是我理想的解决方案,因为我无法在具有“foreach”的函数之外公开 cmd 参数。这需要保留一个实现细节,所以我只想像上面提到的那样传递一个 3 维字典,只是一个键、条件和对象,没有额外的操作。
  • 谢谢,好吧,这似乎很合理。我有两种处理方法
猜你喜欢
  • 2023-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-31
  • 1970-01-01
  • 2022-11-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多