.NET的资源并不限于.resx文件,你可以采用任意存储形式 [上篇]

  为了构建一个轻量级的资源管理框架以满足简单的本地化(Localization)的需求,我试图直接对现有的Resource编程模型进行扩展。虽然最终没能满足我们的需求,但是这两天也算对.NET如何进行资源的存取进行了深入的学习,所以将我对此的认识通过博文的方式与诸位分享。在本篇文章中,我会通过自定义ResourceManager让资源的存储形式不仅仅局限于.ResX文件,你可以根据需要实现任意的存储方式,比如结构化的XML、数据库表,甚至是通过远程访问获取资源。(文中的例子从这里下载)

一、从添加资源文件说起
二、ResourceManager、ResourceSet、ResourceReader与ResourceWriter
三、自定义BinaryResourceManager管理单独二机制资源文件

  一、从添加资源文件(.resx文件)说起

  说起资源,你首先想到的肯定是通过VS添加的扩展名为.resx的资源文件。在这个资源文件中,你不但可以添加单纯的文本资源条目,也可以添加图片、图标、文本文件以及其它类型文件。 不但如此,当你在.resx文件中定义任意类型资源条目的时候,默认定义的代码生成器会为你生成对应的托管代码,使你可以采用强类型编程的方式获取某个条目。

image  比如说,如果你在一个名称为Resources.resx的资源文件中定义了如上图所示的两个字符串资源条目,默认的代码生成器或为你生成如下的代码。

[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技术.NET的资源并不限于.resx文件,你可以采用任意存储形式 [上篇],转载需保留来源!

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。