2013-12-20 53 views
-3

我是初學者,能向我解釋這行代碼嗎?我不明白的代碼行

var button = new KinectTileButton 
{ 
    Label = System.IO.Path.GetFileNameWithoutExtension(file), 
    Background = new ImageBrush(bi) 
}; 
+2

究竟是什麼,你不明白?是C#你不明白嗎?這是基本的對象實例化。 –

+2

[Object Initializers ??](http://msdn.microsoft.com/zh-cn/library/bb384062.aspx) –

回答

3

我認爲它定義了名稱的按鈕,文件沒有它的extenstion的名稱。例如測試,而不是test.txt,然後設置一個背景圖像到按鈕。

0

它定義了一個帶有文件名標籤路徑的按鈕,沒有任何按鈕的擴展和背景。

意思是如果文件名是abc.txt那麼按鈕標籤將只是abc。

1

該代碼是用於創建對象的簡短代碼,與c#4一起出現。 這是此代碼的語法糖:

KinectTileButton button = new KinectTileButton() 

    button.Label = System.IO.Path.GetFileNameWithoutExtension(file), 
    button.Background = new ImageBrush(bi) 
0

「=」後面的代碼是KinectTileButton對象的實例化,該對象的「Label」和Background屬性設置爲其他對象類型。

具體地說,

Label = System.IO.Path.GetFileNameWithoutExtension(file)通過調用「GetFileNameWithoutExtension方法 Background - New ImageBrush(bi)是實例化」的ImageBrush對象並將其分配給背景屬性設置該屬性。

KinectTileButton實例化的這種技術稱爲ObjectInitialiser。你也可以這樣寫:

var button = KinectTileButton(); //assuming there is a parameterless constructor available 
button.Label = System.IO.Path.GetFileNameWithoutExtension(file); 
button.Background = new ImageBrush(bi); 

希望這有助於!