2014-01-06 26 views
0

C#的規範是否阻止從對象的(或結構)初始值設定項構造中調用方法?對象初始化程序中的函數和屬性用法

我問的原因是因爲我試圖使用LINQ-to-XML語句在初始化程序中使用gater數據。這不起作用。但是,如果我在將數據保存到本地變量之前獲取數據,那麼它的工作沒有問題。我只是想知道爲什麼會發生這種情況,因爲我已經找到了我的代碼中的錯誤。

不起作用:

SavedData sData = new SavedData() 
{ 
     exportLocation = data.Root.Descendants("ExportLocation").FirstOrDefault().Value, 
     exportType = (ExportType)data.Root.Descendants("ExportType").FirstOrDefault().Value 
}; 

作品:

var exLoc = data.Root.Descendants("ExportLocation").FirstOrDefault().Value; 
ExportType type = (ExportType)data.Root.Descendants("ExportType").FirstOrDefault().Value; 

Saved Data sData = new SavedData() 
{ 
    exportLocation = exLoc, 
    exportType = type 
}; 
+1

*你的意思是什麼*不起作用*?它編譯對我來說很好。 – MarcinJuraszek

+0

它應該工作。如果你告訴我們它不完全正常工作,我們也許可以幫忙。 – fejesjoco

+0

@MarcinJuraszek _在這種情況下不工作_並不意味着它不能編譯。該對象不會初始化並等於null。 – JNYRanger

回答

1

你可以調用初始化中的方法,所以還有別的東西怎麼回事。

下工作正常,我:

class A 
    { 
     public int x { get; set; } 
    } 

    class B 
    { 
     public int foo() 
     { 
      return 3; 
     } 
    } 

    class Program 
    { 
     static void Main(string[] args) 
     { 
      B data = new B(); 
      A a = new A() { 
       x = data.foo() 
      }; 
     } 
    } 

a.x被設置爲3,那麼它工作正常。

您的代碼在重寫時可能會遇到另一個問題。它也可能是SavedData構造函數正在做的事情,使數據無效。

+0

你是對的。事實證明,我的XML文件存在問題,並且由於它沒有正確解析'ExportType'枚舉值而沒有被封裝爲'Enum.Parse(typeof(ExportType),[LINQ-TO-XML HERE])'謝謝爲了指引我朝着正確的方向。 – JNYRanger