2013-05-12 62 views
2

我的Windows-8應用商店代碼中有一個type-o。我得到了一個奇怪的結果,所以我回去看看,並意識到我錯過了一個價值,但它仍然編譯和運行沒有錯誤。想到這很奇怪,我去了並嘗試在Windows 8控制檯應用程序中,在這種情況下,它是一個編譯錯誤!是什麼賦予了?對象初始值設定項屬性未分配

App store的版本:

var image = new TextBlock() 
      { 
       Text = "A", //Text is "A" 
       FontSize =  //FontSize is set to 100 
       Height = 100, //Height is NaN 
       Width = 100, //Width is 100 
       Foreground= new SolidColorBrush(Colors.Blue) 
      }; 

控制檯版本:

public class test 
{ 
    public int test1 { get; set; } 
    public int test2 { get; set; } 
    public int test3 { get; set; } 
    public int test4 { get; set; } 
} 

class Program 
{ 
    static void Main(string[] args) 
    { 
     test testObject = new test() 
          { 
           test1 = 5, 
           test2 = 
           test3 = 6, //<-The name 'test3' does not exist in the current context       
           test4 = 7 
          }; 
    } 
} 

回答

5

我猜在你的代碼的第一個塊位於曾經的屬性稱爲Height類,所以編譯器被解釋爲:

var image = new TextBlock() 
      { 
       Text = "A", 
       FontSize = this.Height = 100, 
       Width = 100, 
       Foreground = new SolidColorBrush(Colors.Blue) 
      }; 

這也將展開爲什麼你的image.Height屬性是NaN - 你的初始化程序從來沒有試圖設置它。

另一方面,您的第二個代碼塊所在的Program類沒有任何名爲test3的成員,因此編譯器在其上進行了批註。

test testObject = new test(); 
testObject.test1 = 5; 
testObject.test2 = test3 = 6; // What is test3? 
testObject.test4 = 7; 
+0

細看:如果你重寫你的初始化代碼作爲老派的屬性分配

的問題是清晰的。第二個對象確實有'test3'成員。 – 2013-05-12 00:48:56

+0

他正在創建一個名爲'test3'的屬性的'test'類,是的,但是周圍的類('Program')沒有 - 他試圖給屬性testObject分配一個名爲test3的值.test2',編譯器在當前上下文中找不到該名稱的變量或屬性,所以它不喜歡它。 – 2013-05-12 00:50:55

+0

+1 - 我明白你在說什麼。接得好! – 2013-05-12 00:53:19

相關問題