List<T>.ForEach(Action<T>) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
對 的 List<T>每個元素執行指定動作。
public:
void ForEach(Action<T> ^ action);
public void ForEach(Action<T> action);
member this.ForEach : Action<'T> -> unit
Public Sub ForEach (action As Action(Of T))
參數
例外狀況
action 是 null。
收藏中的一個元素已被修改。
範例
以下範例示範使用 Action<T> 代理來列印物件內容 List<T> 。 在此範例中,該 Print 方法用於將清單內容顯示給主控台。
Note
除了使用 Print 該方法顯示內容外,C# 範例還展示了如何使用 匿名方法 將結果顯示給主控台。
List<string> names = new List<string>();
names.Add("Bruce");
names.Add("Alfred");
names.Add("Tim");
names.Add("Richard");
// Display the contents of the list using the Print method.
names.ForEach(Print);
// The following demonstrates the anonymous method feature of C#
// to display the contents of the list to the console.
names.ForEach(delegate(string name)
{
Console.WriteLine(name);
});
void Print(string s)
{
Console.WriteLine(s);
}
/* This code will produce output similar to the following:
* Bruce
* Alfred
* Tim
* Richard
* Bruce
* Alfred
* Tim
* Richard
*/
Imports System.Collections.Generic
Class Program
Shared Sub Main()
Dim names As New List(Of String)
names.Add("Bruce")
names.Add("Alfred")
names.Add("Tim")
names.Add("Richard")
' Display the contents of the list using the Print method.
names.ForEach(AddressOf Print)
End Sub
Shared Sub Print(ByVal s As String)
Console.WriteLine(s)
End Sub
End Class
' This code will produce output similar to the following:
' Bruce
' Alfred
' Tim
' Richard
備註
是 Action<T> 對傳送給它的物件執行動作的方法的代理。 電流 List<T> 的元素會分別傳給 Action<T> 代表。
此方法為 O(n) 運算,其中 n 為 Count。
修改代理主體 Action<T> 底層集合不被支援,且會導致行為未定義。