0
我懷疑我對被動擴展的理解是錯誤的,但我會認爲它們可以用來訂閱對某個集合的方法調用。我正在考慮一個dotnet中的典型事件處理程序。我的最終目標是在集合被修改時觸發方法調用。無效擴展混淆
我有以下小控制檯應用程序示例,正如您在評論中看到的那樣,我期待它重新打印結果或至少在將其添加到集合中時重新打印上次結果。我也嘗試query.ToList()來查看是否重新運行查詢將再次打印結果。
static void Main(string[] args)
{
// we have some data that is an IEnumerable It's lazy so we can query it.
IEnumerable<int> data = new List<int>();
for (int i = 0; i < 10; i++)
{
(data as List<int>).Add(i);
}
// create a linq query
var query = from number in data select number;
// create observable
IObservable<int> observableQuery = query.ToObservable<int>(Scheduler.Default);
observableQuery.Subscribe(Console.WriteLine);
/// the numbers get printed here 1.. 9
Console.ReadKey();
(data as List<int>).Add(1000);
var l = query.ToList();
var j = observableQuery.ToList();
// the numbers don't get reprinted here... ? Shouldn't they reprint when the collection is modified?
Console.ReadKey();
}
https://msdn.microsoft.com/en-us/library/hh212140(v=vs.103).aspx通過這個,你沒有錯誤。但你有一個參考問題。查詢和數據具有不同的參考值。更新數據時,查詢不受影響。因此,收集沒有修改 – misha130
@ misha130我知道這不是一個參考。我試圖弄清楚Rx是什麼。我認爲從發佈這個問題以來我一直在閱讀的是它只是在線程中運行查詢。我仍然沒有得到所有的炒作,但我相信這只是因爲我不明白它是什麼。 –
如果你想對集合中的變化做出反應,你可能更喜歡使用'ObservableCollection',請參閱http://stackoverflow.com/questions/4279185/what-is-the-use-of-observablecollection-in- net –