如何在foreach的每次迭代中执行函数

时间:2014-11-26 13:01:15

标签: c# .net loops static

我在类中有一个静态方法,我从foreach循环中的另一个类调用。问题是该方法实际执行一次。如何在每次迭代中制作它?

编辑:我更新了完整的B类。问题是绑定到我的xaml的List枚举ListBox只用最后的_bing填充。

A类:

foreach (Bing bing in MyBingsCollection)
{
    MyViewModel.GetBingVar(bing);
}

B类:

public class MyViewModel : INotifyPropertyChanged
{
    static Bing _bing;

    public MyViewModel()
    {

    }

    public static void GetBingVar(Bing bing) // EDIT
    {
        _bing = bing;
    }

    public IEnumerable Parts
    {
        get
        {
            if (null != _bing)
            {
                if (typeof(MyType1) == _bing.Item.GetType())
                {
                    ObservableCollection<MyType1> MyType1ItemsCollection = new ObservableCollection<MyType1>();

                    MyType1ItemsCollection.Add(..);

                    return MyType1ItemsCollection;
                }
                else if (typeof(MyType2) == _bing.Item.GetType())
                {
                    ObservableCollection<MyType2> MyType2ItemsCollection = new ObservableCollection<MyType2>();

                    MyType2ItemsCollection.Add(..);

                    return MyType2ItemsCollection;
                }
            }

            return new ObservableCollection<object>();
        }
        set
        {
            NotifyPropertyChanged("Parts");
        }
    }

    #region Prop changed
    public event PropertyChangedEventHandler PropertyChanged;
    private void NotifyPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (null != handler)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
    #endregion
}

1 个答案:

答案 0 :(得分:1)

如果MyBingsCollection有1个项目,则GetBingVar将被调用一次。如果它有更多的项目,它将被调用更多次。

在任何情况下,如果GetBingVar每次调用时都覆盖相同的字段_bing,它将看起来,就像它只调用一次一样(并且只针对最后一项) )因为每次调用都会撤消先前调用的内容。