2017-01-19 21 views
0

例如說我有這樣的一類:C#檢查,如果裁判名單<>內容已經改變

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); 

有沒有一種簡單的方法如果引用List<int>的內容已更改,請檢查myNewClass對象?例如如果列表中的任意隨機整數發生變化,則引發myNewClass對象中的事件。

+5

使用'ObservableCollection',而不是'List'。另外,不要使用'ref'。在C#中,'myIntegerList' *已經*是一個對象的引用。只需傳入參考。 –

+1

你不需要使用'ref'。你只需要,如果你想分配傳入的參數到別的東西,並且改變了你通過的變量。 – juharr

回答

1

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); 
+0

不得不更新一個4年的代碼庫來使它工作,但它是值得的。謝謝! 另一個快速的問題是,有沒有一種方法可以使用ref來確保當一個項目從列表中刪除時,它也會從另一個列表中刪除?基本上我希望有一個列表包含對另一個列表中的項目的引用,並且能夠同時刪除而不必使用事件。 –

+0

@GryffDavid它絕對必須是兩個不同的集合對象嗎?它可以完成,但我寧願通過共享一個單一的集合來做到這一點。 –

+0

這是一個奇怪的情況。這是一款遊戲。第二個列表只包含原始列表中的一些項目,並且原始列表中的相同項目最終可能會在任何時候被刪除,而我需要將更改回顯到第二個列表。 –

相關問題