簡介
字元串字面量(stringliteral)是指雙引號引住的一系列字元,雙引號中可以沒有字元,可以只有一個字元,也可以有很多個字元。
編碼
字面量作為一種通用的,跨平台的數據交換格式,在程式界是公認的事實;而.NetFramework以前的版本中麻煩的XML操作,常常令程式設計師心生不快。記得以前試圖生成一個XML檔案,無非是兩種模式:用StringBuilder拼接XML字元串,或者是用XMLDocument/XMLWriter進行DOM操作。StringBuilder是有足夠的速度,但是沒有穩定性的保障,需要多次過濾以保護XML檔案的完整性。而使用MSXML的包裝System.Xml進行操作,又未免太麻煩了些。 字面量功能是VisualBasic9為解放程式設計師勞力作出的一項非常大的改進,它可讓程式設計師直接在代碼中嵌入XML進行生成操作。藉助編譯器的力量,XML字面量調用System.Xml.Linq進行XML的動態生成。在C#中,雖然同樣可以調用這個命名空間下的類進行生成,但是遠沒有VisualBasic的模式輕鬆,省力。舉一個簡單的範例,用於動態生成一個XML文檔:
舊的StringBuilder模式:
ImportsSystem.Text
PublicFunctionBuildXMLFromStringBuilder()FunctionBuildXMLFromStringBuilder(NameAsString,AgeAsInteger)AsString
DimXMLBuilderAsNewStringBuilder
WithXMLBuilder
.AppendLine("")
.Append("")
.Append(Name)
.AppendLine("")
.Append("")
.Append(Age)
.AppendLine("")
.AppendLine("")
EndWith
舊的XMLDOM模式:
PublicFunctionBuildXMLFromXmlDom()FunctionBuildXMLFromXmlDom(ByValNameAsString,ByValAgeAsInteger)AsString
DimXMLDocumentAsNewXmlDocument
DimRootElementAsXmlElement=XMLDocument.CreateElement("Person")
DimNameElementAsXmlElement=XMLDocument.CreateElement("Name")
DimAgeElementAsXmlElement=XMLDocument.CreateElement("Age")
WithRootElement
.AppendChild(NameElement)
.AppendChild(AgeElement)
EndWith
WithNameElement
.Value=Name
EndWith
WithAgeElement
.Value=CStr(Age)
EndWith
XMLDocument.AppendChild(RootElement)
ReturnXMLDocument.ToString()
EndFunction
新的XML字面量:
PublicFunctionBuildXMLFromXLinq()FunctionBuildXMLFromXLinq(ByValNameAsString,ByValAgeAsInteger)AsString
Return
.ToString()
EndFunction