Dart編程語言支持method cascades。方法級聯將實現下面的Silverlight/WPF的C#代碼:C中的模擬方法級聯#
var listBox = new ListBox();
listBox.Width = 200;
listBox.MouseEnter += (s, e) => Console.WriteLine("MouseEnter");
var button1 = new Button() { Content = "abc" };
button1.Click += (s, e) => Console.WriteLine("button1.Click");
listBox.Items.Add(button1);
var button2 = new Button() { Content = "def" };
button2.Click += (s, e) => Console.WriteLine("button2.Click");
listBox.Items.Add(button2);
ContentPanel.Children.Add(listBox);
寫入,而不是爲:
ContentPanel.Children.Add(
new ListBox()
..Width = 200
..MouseEnter += ((s, e) => Console.WriteLine("MouseEnter"))
..Items.Add(
new Button()
..Content = "abc";
..Click += ((s, e) => Console.WriteLine("button 1 Click")))
..Items.Add(
new Button()
..Content = "def";
..Click += (s, e) => (Console.WriteLine("button 2 Click"))));
我的問題是,有沒有辦法來模擬或密切近似方法級聯在C#中?
這是我想出的一種方法。鑑於這種擴展方法:
public static T Call<T>(this T obj, Action<T> proc)
{
proc(obj);
return obj;
}
上面的例子可以按如下方式寫入:
ContentPanel.Children.Add(
new ListBox().Call(o => {
o.Width = 200;
o.MouseEnter += (s, e) => Console.WriteLine("MouseEnter");
o.Items.Add(
new Button().Call(b => {
b.Content = "abc";
b.Click += (s, e) => Console.WriteLine("button 1 Click"); }));
o.Items.Add(
new Button().Call(b => {
b.Content = "def";
b.Click += (s, e) => Console.WriteLine("button 2 Click"); })); }));
我不認爲這是相當。 :-)但它本質上確保了應用流暢的風格。
任何進一步的細節,你根本就沒有找[對象初始](http://msdn.microsoft.com/en-us/library/vstudio/bb384062.aspx)? –
@SimonWhitehead對象初始值設定項僅適用於屬性。該示例包含事件和方法調用。 – juharr
我認爲你所擁有的儘可能接近你所能得到的。我真的不認爲這比你的Dart例子更醜陋。 – juharr