2014-12-04 65 views
-2

該代碼時產生錯誤:「使用未分配的局部變量的」錯誤傳遞ref參數

used of unassigned local variable 'namespace2'

XNamespace namespace2; 
string partText = Declaration.partText; 
Declaration.partText = string.Empty; 
string str = ""; 
IEnumerable<XElement> source = InputXDoc.Descendants(Function.GetNamespace(ref namespace2, "").GetName("body")); 
if (source.Descendants<XElement>(Function.GetNamespace(ref namespace2, "").GetName("div")).Count<XElement>() > 0) 
{ 
    IEnumerable<XElement> introduced5 = InputXDoc.Descendants(Function.GetNamespace(ref namespace2, "").GetName("body")); 
    if (introduced5.Descendants<XElement>(Function.GetNamespace(ref namespace2, "").GetName("div")).First<XElement>().Attributes("id").Count<XAttribute>() > 0) 
    { 
     IEnumerable<XElement> introduced6 = InputXDoc.Descendants(Function.GetNamespace(ref namespace2, "").GetName("body")); 
     this.ChapterName = introduced6.Descendants<XElement>(Function.GetNamespace(ref namespace2, "").GetName("div")).First<XElement>().Attributes("id").First<XAttribute>().Value; 
    } 
} 

爲什麼我會遇到這樣的?

+1

對我來說,錯誤信息很清楚。這裏沒有包含行號,但我確定編譯器正在向您報告。所以你應該確切知道錯誤發生的位置。你可以親眼看到你永遠不會初始化'namespace2'。不幸的是,你沒有提供足夠的信息讓我們知道變量應該被初始化。 – 2014-12-04 00:55:47

回答

2

MSDNref

An argument that is passed to a ref parameter must be initialized before it is passed. This differs from out parameters, whose arguments do not have to be explicitly initialized before they are passed. For more information, see out.

,所以你需要寫:

XNamespace namespace2 = null; 

它總是很好的做法,反正初始化變量!

注:我初始化null因爲我不知道要被初始化爲你的參數實際上需要做。檢查你正在調用的函數的文檔,你可能需要它是別的東西。

+0

毫無疑問,這將修復編譯器錯誤。但是OP真的需要做什麼?你確定'Function.GetNamespace()'不需要參數是非空嗎? 'ref'參數通常是'ref'而不是'out',因爲方法期望它們有一個可用的值來啓動。 – 2014-12-04 00:54:11

+0

@PeterDuniho我不知道。我會期望它被初始化爲其他東西,但是不知道被調用函數的內部工作情況,我不能肯定地說。我會編輯提到它。這裏 – BradleyDotNET 2014-12-04 00:55:50

+0

@PeterDuniho是裁判,我稱之爲.. 公共靜態的XNamespace GetNamespace(REF的XNamespace XNS,串NS) { 如果(XNS == NULL){ XNS = XNamespace.Get(NS); } return xns; } 非常感謝。 – LuluErwin 2014-12-18 00:24:02

相關問題