為了構(gòu)建一個輕量級的資源管理框架以滿足簡單的本地化(Localization)的需求,我試圖直接對現(xiàn)有的Resource編程模型進(jìn)行擴展。雖然最終沒能滿足我們的需求,但是這兩天也算對.NET如何進(jìn)行資源的存取進(jìn)行了深入的學(xué)習(xí),所以將我對此的認(rèn)識通過博文的方式與諸位分享。在本篇文章中,我會通過自定義ResourceManager讓資源的存儲形式不僅僅局限于.ResX文件,你可以根據(jù)需要實現(xiàn)任意的存儲方式,比如結(jié)構(gòu)化的XML、數(shù)據(jù)庫表,甚至是通過遠(yuǎn)程訪問獲取資源。(文中的例子從這里下載)
一、從添加資源文件說起
二、ResourceManager、ResourceSet、ResourceReader與ResourceWriter
三、自定義BinaryResourceManager管理單獨二機制資源文件
一、從添加資源文件(.resx文件)說起
說起資源,你首先想到的肯定是通過VS添加的擴展名為.resx的資源文件。在這個資源文件中,你不但可以添加單純的文本資源條目,也可以添加圖片、圖標(biāo)、文本文件以及其它類型文件。 不但如此,當(dāng)你在.resx文件中定義任意類型資源條目的時候,默認(rèn)定義的代碼生成器會為你生成對應(yīng)的托管代碼,使你可以采用強類型編程的方式獲取某個條目。
比如說,如果你在一個名稱為Resources.resx的資源文件中定義了如上圖所示的兩個字符串資源條目,默認(rèn)的代碼生成器或為你生成如下的代碼。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Demo.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
internal static string Greeting4Chris {
get {
return ResourceManager.GetString("Greeting4Chris", resourceCulture);
}
}
internal static string Greeting4NewYear {
get {
return ResourceManager.GetString("Greeting4NewYear", resourceCulture);
}
}
}
NET技術(shù):.NET的資源并不限于.resx文件,你可以采用任意存儲形式 [上篇],轉(zhuǎn)載需保留來源!
鄭重聲明:本文版權(quán)歸原作者所有,轉(zhuǎn)載文章僅為傳播更多信息之目的,如作者信息標(biāo)記有誤,請第一時間聯(lián)系我們修改或刪除,多謝。