【问题标题】:ForEach error in a observablecollection [duplicate]可观察集合中的 ForEach 错误 [重复]
【发布时间】:2017-07-14 20:48:41
【问题描述】:

我对 observablecollection 中的 ForEach 有疑问。 Visual Studio 告诉我:

“'observablecollection' 不包含 'ForEach' 定义,并且在接受第一个 'observablecollection' 类型参数的 'ForEach' 扩展方法中找不到。可能缺少使用或引用程序集的指令"

问题是,另一个项目中的类似代码可以正常工作,但在这个新项目中却不行。我哪里错了?

谢谢

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ProvaBindingXaml
{
   /* public class Impiegato
    {

        public string Nome { get; set; }
        public string Cognome { get; set; }
        public string Matricola { get; set; }

    }
    */

    public class Rule
    {
        public string Ruolo { get; set; }

        public Rule(string ruolo)
        {
            this.Ruolo = ruolo;
        }

        public override string ToString()
        {
            return this.Ruolo;
        }

        public static ObservableCollection<Rule> GetAllRules()
        {
            var CollectionRuoli = new ObservableCollection<Rule>();
            CollectionRuoli.Add(new Rule ("Impiegato"));
            CollectionRuoli.Add(new Rule ("Dirigente"));
            CollectionRuoli.Add(new Rule ("Operaio"));
            CollectionRuoli.Add(new Rule ("Manutentore"));
            CollectionRuoli.Add(new Rule ("Presidente"));
            return CollectionRuoli;

        }


        public static void GetComboBoxList(ObservableCollection<Rule> RuleItems)
        {
            var allItems = GetAllRules();
            RuleItems.Clear();
            allItems.ForEach(p => RuleItems.Add(p));
        }
    }
}

【问题讨论】:

标签: c# visual-studio foreach win-universal-app observablecollection


【解决方案1】:

ObservableCollection 没有ForEach 方法。

我怀疑你可能会想到 ListForEach - 但 List 是不同的类型。

我会考虑使用foreach 循环,或者在使用ForEach 之前调用ToList

【讨论】:

  • 好的,但是为什么它在另一个项目中的这段代码有效? s13.postimg.org/rhyiw3vkn/Immagine.png
  • 在另一个项目中,转到ForEach 行并右键单击Go To Implementation。我的猜测是有人在那里写了一个扩展方法,但你需要检查并向我们确认。
  • 是的:有这个代码namespace WinRTXamlToolkit.Tools { public static class EnumerableExtensions { public static void ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; list, Action&lt;T&gt; action); public static List&lt;T&gt; Shuffle&lt;T&gt;(this IEnumerable&lt;T&gt; list); } }哦,我想我明白了!!!谢谢
  • 嗯,这就是为什么它在那里工作而不是在你的。还要检查我和 Felipe 提供的与您的原始帖子的链接。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-08-14
  • 2019-02-23
相关资源
最近更新 更多