2013-03-30 65 views
0

我有一個類如何實現Action委託?

public class TextBoxConfig 
    { 
     public string Caption { get; set; } 
     public string FieldName { get; set; } 
     public int Width { get; set; } 
     public string Name { get; set; } 
    } 

和另一工具類,其具有接受TextBoxConfig作爲這樣

public class Util 
    { 
     public static TextBox ApplySettings(TextBoxConfig config) 
     { 
     //Doing something 
     } 
    } 

一般來說,我可以調用的Util類ApplySettings方法這樣

的參數的方法
TextBoxConfig config = new TextBoxConfig(); 
    config.Caption = "Name"; 
    config.FieldName = "UserName" 
    config.Width = 20; 
    config.Name = "txtName"; 

    TextBox txt = Util.ApplySettings(config); 

但我想將參數傳遞給ApplySettings像這樣

TextBox txt = Util.ApplySettings(o => 
    { 
     o.Caption = "Name"; 
     o.FieldName = "UserName" 
     o.Width = 20; 
     o.Name = "txtName"; 
    });    

請建議我我該怎麼辦呢..

回答

0

好吧,自己動手:這裏是一樣的東西,只是用lambda表達式強制執行。我不得不在語句後添加一些分號。我更喜歡其他答案。但我希望這能滿足你對lambda表達式的渴望。

+0

+1:回答這個問題(不管它聽起來多麼荒謬; p) – leppie

+0

很好......謝謝Das :) –

0

不完全一樣,你的願望,但八九不離十:

TextBox txt = Util.ApplySettings(new TextBoxConfig() 
{ 
    Caption = "Name", 
    FieldName = "UserName", 
    Width = 20, 
    Name = "txtName" 
}); 

注意每次設置後的逗號。請參閱http://msdn.microsoft.com/en-us/library/vstudio/bb397680.aspx

+0

感謝您的評論這與我創建實例一樣,但我想使用Lambda表達式。 –

+0

@Neeraj Gupta,爲了什麼? Lambda是一個函數,但你沒有傳遞函數。 – aush

+0

設置TextBoxConfig類的屬性,因爲我要求設置 –