C#检查ref list<>内容已经改变

时间:2017-01-19 18:07:11

标签: c# list events ref

比如说我在课堂上有这个:

List<int> myIntegerList;

public MyClass(ref List<int> intList)
{
    myIntegerList= intList;
}

这是我的主要课程:

List<int> myIntegerList = new List<int>();
MyClass myNewClass;

for (int i = 0; i < 10; i++)
{
    myIntegerList .Add(Random.Next(0, 100));
}

myNewClass = new MyClass(ref IntegerList);

如果引用的myNewClass的内容发生了变化,是否可以轻松检入List<int>对象?例如如果列表中的任何随机整数发生更改,则会在myNewClass对象中引发事件。

2 个答案:

答案 0 :(得分:2)

List<T>不会这样做,但ObservableCollection<T>会。另外,不要在构造函数中使用ref参数;任何引用类实例的C#变量都是引用。类类型的ref参数是引用的引用,您不需要这些引用,也可能不想考虑它们。

using System.Collections.ObjectModel;

public class MyClass
{
    private ObservableCollection<int> _integerList;

    //  Do not make this a ref parameter, it's a reference already
    public MyClass(ObservableCollection<int> intList)
    {
        _integerList = intList;
        _integerList.CollectionChanged += _integerList_CollectionChanged;
    }

    private void _integerList_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        //  Do stuff here in response to changed values in the list. 

        //  Now back to the reference thing again: int is immutable.
        //  You can't change it, you can only replace it with another 
        //  int. This event will be raised when you do that. 
        //
        //  If the objects in the ObservableCollection are class 
        //  instances rather than ints, they're mutable. You can 
        //  change their properties without replacing them. 
        //  ObservableCollection cannot know when that happens, so 
        //  it can't tell you. 
        //
        //  In that case, you'd need the class to implement 
        //  INotifyPropertyChanged. That's a different can of worms, 
        //  but it's a manageable one. 
    }
}

...

ObservableCollection<int> ints = new ObservableCollection<int>();
MyClass myNewClass;
var r = new Random();

for (int i = 0; i < 10; i++)
{
    ints.Add(r.Next(0, 100));
}

myNewClass = new MyClass(ints);

答案 1 :(得分:1)

使用ObservableCollection..check以下链接以供进一步参考

ObservableCollection msdn