C# Resources资源详解

2019-12-30 15:51:54刘景俊


// Load ResourcesSample.MainForm.resources from MainForm.resx
ResourceManager resman =new ResourceManager(this.GetType());

// Access the MyString string resource from the ResourceManager
// (these two techniques are equivalent for strings)
string s1 = (string)resman.GetObject("MyString");
string s2 = resman.GetString("MyString");

(6) 强类型资源类

Resource Manager 提供了对资源的弱类型方法GetObject来返回资源,需要进行类型转换。但是VS2005和一个自定义工具 ResXFileCodeGenerator 提供了对这个问题的解决办法。当一个 .resx 文件被保存时,VS2005会应用自定义工具将其产生一个相应的 .Designer.cs 文件,此文件提供了一个名字和 .resx 文件相同的类,这个类所处的命名空间为 defaultNamespace.projectPath。

 


namespace ResourcesSample {
  ///<summary>
  ///    A strongly typed resource class, for looking up localized
  ///    strings, etc.
  ///</summary>
  // This class was autogenerated by the StronglyTypedResourceBuilder
  // class via a tool like ResGen or Visual Studio.
  // To add or remove a member, edit your .resx file and then rerun ResGen
  // with the /str option, or rebuild your VS project.
  internalclass MyResources {
   static global::System.Resources.ResourceManager resourceMan;
   static global::System.Globalization.CultureInfo resourceCulture;

   internal MyResources() {}

   ///<summary>
   ///  Returns the cached ResourceManager instance used by this
   ///  class.
   ///</summary>
   internalstatic global::
    System.Resources.ResourceManager ResourceManager {
    get {
     if( (resourceMan ==null) ) {
      global::System.Resources.ResourceManager temp =
       new global::System.Resources.ResourceManager(
        "ResourcesSample.MyResources",
        typeof(MyResources).Assembly);
      resourceMan = temp;
     }
     return resourceMan;
    }
   }

   ///<summary>
   ///  Overrides the current thread's CurrentUICulture property for
   ///  all resource lookups using this strongly typed resource class.
   ///</summary>
   internalstatic global::System.Globalization.CultureInfo Culture {
    get { return resourceCulture; }
    set { resourceCulture = value; }
   }
  }
}

由以上可以看出 MyResource 类型的两个特征:

a. 它通过一个ResourceManager类型的属性提供了对ResourceManager的静态访问,就没必要写之前的创建逻辑了; b. 通过一个Culture属性提供了CultureInfo对象实现对本地化信息的静态访问;

提供的每个资源都是强类型静态只读属性。在内部实现中,每个属性都由设计器生成的资源类利用托管的ResourceMananger对象产生的;


// Access strongly typed resources from MyResources.resx
string myString = MyResources.MyString;
Icon myIcon = MyResources.MyIcon;