ResourceManager 类

定义

表示资源管理器,其可在运行时提供对于特定文化资源的便利访问Represents a resource manager that provides convenient access to culture-specific resources at run time.

public ref class ResourceManager
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class ResourceManager
type ResourceManager = class
Public Class ResourceManager
继承
ResourceManager
派生
属性

示例

下面的示例演示如何使用显式区域性和隐式当前 UI 区域性从主程序集和附属程序集获取字符串资源。The following example demonstrates how to use an explicit culture and the implicit current UI culture to obtain string resources from a main assembly and a satellite assembly. 有关详细信息,请参阅创建附属程序集主题的 "不在全局程序集缓存中安装附属程序集的目录位置" 部分。For more information, see the "Directory Locations for Satellite Assemblies Not Installed in the Global Assembly Cache" section of the Creating Satellite Assemblies topic.

若要运行此示例:To run this example:

  1. 在应用目录中,创建一个名为 rmc 的文件,其中包含以下资源字符串:In the app directory, create a file named rmc.txt that contains the following resource strings:

    
    day=Friday  
    year=2006  
    holiday="Cinco de Mayo"  
    
    
  2. 使用资源文件生成器,按如下所示从 rmc 输入文件生成 rmc 资源文件:Use the Resource File Generator to generate the rmc.resources resource file from the rmc.txt input file as follows:

    resgen rmc.txt  
    
  3. 创建应用程序目录的子目录,并将其命名为 "es-MX"。Create a subdirectory of the app directory and name it "es-MX". 这是将在接下来的三个步骤中创建的附属程序集的区域性名称。This is the culture name of the satellite assembly that you will create in the next three steps.

  4. 在包含以下资源字符串的 rmc.es 目录中创建一个名为-MX 的文件:Create a file named rmc.es-MX.txt in the es-MX directory that contains the following resource strings:

    
    day=Viernes  
    year=2006  
    holiday="Cinco de Mayo"  
    
    
  5. 使用资源文件生成器生成 rmc.es-mx 输入文件中的 rmc.es 资源文件,如下所示:Use the Resource File Generator to generate the rmc.es-MX.resources resource file from the rmc.es-MX.txt input file as follows:

    resgen rmc.es-MX.txt  
    
  6. 假设此示例的文件名为 rmc 或 rmc.cs。Assume that the filename for this example is rmc.vb or rmc.cs. 将以下源代码复制到一个文件中。Copy the following source code into a file. 然后对其进行编译,并在可执行程序集中嵌入主程序集资源文件 rmc。Then compile it and embed the main assembly resource file, rmc.resources, in the executable assembly. 如果使用 Visual Basic 编译器,则语法为:If you are using the Visual Basic compiler, the syntax is:

    vbc rmc.vb /resource:rmc.resources  
    

    C#编译器的相应语法为:The corresponding syntax for the C# compiler is:

    csc /resource:rmc.resources rmc.cs  
    
  7. 使用程序集链接器创建附属程序集。Use the Assembly Linker to create a satellite assembly. 如果应用的基名称是 rmc,则附属程序集名称必须为 rmc。If the base name of the app is rmc, the satellite assembly name must be rmc.resources.dll. 应在 es MX 目录中创建附属程序集。The satellite assembly should be created in the es-MX directory. 如果是当前目录,请使用以下命令:If es-MX is the current directory, use this command:

    al /embed:rmc.es-MX.resources /c:es-MX /out:rmc.resources.dll   
    
  8. 运行 rmc 以获取并显示嵌入的资源字符串。Run rmc.exe to obtain and display the embedded resource strings.

using System;
using System.Resources;
using System.Reflection;
using System.Threading;
using System.Globalization;

class Example 
{
    public static void Main() 
    {
    string day;
    string year;
    string holiday;
    string celebrate = "{0} will occur on {1} in {2}.\n";

    // Create a resource manager. 
    ResourceManager rm = new ResourceManager("rmc", 
                             typeof(Example).Assembly);

    Console.WriteLine("Obtain resources using the current UI culture.");

    // Get the resource strings for the day, year, and holiday 
    // using the current UI culture. 
    day  = rm.GetString("day");
    year = rm.GetString("year");
    holiday = rm.GetString("holiday");
    Console.WriteLine(celebrate, holiday, day, year);

    // Obtain the es-MX culture.
    CultureInfo ci = new CultureInfo("es-MX");

    Console.WriteLine("Obtain resources using the es-MX culture.");

   // Get the resource strings for the day, year, and holiday 
   // using the specified culture. 
    day  = rm.GetString("day", ci);
    year = rm.GetString("year", ci);
    holiday = rm.GetString("holiday", ci);
// ---------------------------------------------------------------
// Alternatively, comment the preceding 3 code statements and 
// uncomment the following 4 code statements:
// ----------------------------------------------------------------
// Set the current UI culture to "es-MX" (Spanish-Mexico).
//    Thread.CurrentThread.CurrentUICulture = ci;

// Get the resource strings for the day, year, and holiday 
// using the current UI culture. Use those strings to 
// display a message. 
//    day  = rm.GetString("day");
//    year = rm.GetString("year");
//    holiday = rm.GetString("holiday");
// ---------------------------------------------------------------

// Regardless of the alternative that you choose, display a message 
// using the retrieved resource strings.
    Console.WriteLine(celebrate, holiday, day, year);
    }
}
/*
This example displays the following output:

   Obtain resources using the current UI culture.
   "5th of May" will occur on Friday in 2006.
   
   Obtain resources using the es-MX culture.
   "Cinco de Mayo" will occur on Viernes in 2006.
*/
Imports System.Resources
Imports System.Reflection
Imports System.Threading
Imports System.Globalization

Class Example
    Public Shared Sub Main() 
        Dim day As String
        Dim year As String
        Dim holiday As String
        Dim celebrate As String = "{0} will occur on {1} in {2}." & vbCrLf

        ' Create a resource manager. 
        Dim rm As New ResourceManager("rmc", GetType(Example).Assembly)

        Console.WriteLine("Obtain resources using the current UI culture.")

        ' Get the resource strings for the day, year, and holiday 
        ' using the current UI culture. 
        day = rm.GetString("day")
        year = rm.GetString("year")
        holiday = rm.GetString("holiday")
        Console.WriteLine(celebrate, holiday, day, year)

        ' Obtain the es-MX culture.
        Dim ci As New CultureInfo("es-MX")

        Console.WriteLine("Obtain resources using the es-MX culture.")

        ' Get the resource strings for the day, year, and holiday 
        ' using the es-MX culture.  
        day = rm.GetString("day", ci)
        year = rm.GetString("year", ci)
        holiday = rm.GetString("holiday", ci)

        ' ---------------------------------------------------------------
        ' Alternatively, comment the preceding 3 code statements and 
        ' uncomment the following 4 code statements:
        ' ----------------------------------------------------------------
        ' Set the current UI culture to "es-MX" (Spanish-Mexico).
        '    Thread.CurrentThread.CurrentUICulture = ci
        ' Get the resource strings for the day, year, and holiday 
        ' using the current UI culture. 
        '    day  = rm.GetString("day")
        '    year = rm.GetString("year")
        '    holiday = rm.GetString("holiday")
        ' ---------------------------------------------------------------

        ' Regardless of the alternative that you choose, display a message 
        ' using the retrieved resource strings.
        Console.WriteLine(celebrate, holiday, day, year)
    End Sub 
End Class
' This example displays the following output:
'Obtain resources using the current UI culture.
'"5th of May" will occur on Friday in 2006.
'
'Obtain resources using the es-MX culture.
'"Cinco de Mayo" will occur on Viernes in 2006.

注解

重要

使用不受信任的数据调用此类中的方法存在安全风险。Calling methods from this class with untrusted data is a security risk. 仅使用受信任的数据调用此类中的方法。Call the methods from this class only with trusted data. 有关详细信息,请参阅数据验证For more information, see Data Validation.

ResourceManager类从嵌入在程序集或独立 .resources 文件中的二进制 .resources 文件中检索资源。The ResourceManager class retrieves resources from a binary .resources file that is embedded in an assembly or from a standalone .resources file. 如果已在附属程序集中部署了已本地化和已本地化的资源,则该应用程序会查找特定于区域性的资源,在已本地化的资源不存在时提供资源回退,并支持资源序列化。If an app has been localized and localized resources have been deployed in satellite assemblies, it looks up culture-specific resources, provides resource fallback when a localized resource does not exist, and supports resource serialization.

有关在桌面应用和Windows 8.x 应用商店Windows 8.x Store应用中创建和管理资源的详细信息,请参阅以下部分:For more information about creating and managing resources in desktop apps and Windows 8.x 应用商店Windows 8.x Store apps, see the following sections:

桌面应用Desktop Apps

对于桌面应用程序, ResourceManager类从二进制资源(.resources)文件中检索资源。For desktop apps, the ResourceManager class retrieves resources from binary resource (.resources) files. 通常,语言编译器或程序集链接器(al.exe)将这些资源文件嵌入到程序集中。Typically, a language compiler or the Assembly Linker (AL.exe) embeds these resource files in an assembly. ResourceManager 通过CreateFileBasedResourceManager调用方法,还可以使用对象直接从未嵌入到程序集的 .resources 文件中检索资源。You can also use a ResourceManager object to retrieve resources directly from a .resources file that is not embedded in an assembly, by calling the CreateFileBasedResourceManager method.

注意

使用 ASP.NET 应用程序中的独立 .resources 文件将中断 XCOPY 部署,因为在ReleaseAllResources方法显式释放资源之前,这些资源将一直保持锁定状态。Using standalone .resources files in an ASP.NET app will break XCOPY deployment, because the resources remain locked until they are explicitly released by the ReleaseAllResources method. 如果要将资源与 ASP.NET 应用程序一起部署,应将 .resources 文件编译为附属程序集。If you want to deploy resources with your ASP.NET apps, you should compile your .resources files into satellite assemblies.

在基于资源的应用程序中,一个 .resources 文件包含默认区域性的资源,如果找不到特定于区域性的资源,则使用其资源。In a resource-based app, one .resources file contains the resources of the default culture whose resources are used if no culture-specific resources can be found. 例如,如果应用的默认区域性为英语(en),则当找不到特定区域性的本地化资源(例如英语(美国)(en-us)或法语(法国)(fr))时,将使用英语资源。For example, if an app's default culture is English (en), the English language resources are used whenever localized resources cannot be found for a specific culture, such as English (United States) (en-US) or French (France) (fr-FR). 通常,默认区域性的资源嵌入主应用程序集中,其他本地化的区域性的资源嵌入在附属程序集中。Typically, the resources for the default culture are embedded in the main app assembly, and resources for other localized cultures are embedded in satellite assemblies. 附属程序集只包含资源。Satellite assemblies contain only resources. 它们与主程序集具有相同的根文件名,扩展名为 .resources。They have the same root file name as the main assembly and an extension of .resources.dll. 对于其程序集未在全局程序集缓存中注册的应用程序,附属程序集存储在其名称与程序集的区域性相对应的应用程序子目录中。For apps whose assemblies are not registered in the global assembly cache, satellite assemblies are stored in an app subdirectory whose name corresponds to the assembly's culture.

创建资源Creating Resources

开发基于资源的应用时,会将资源信息存储在文本文件(扩展名为 .txt 或 .restext 的文件)或 XML 文件(扩展名为 .resx 的文件)中。When you develop a resource-based app, you store resource information in text files (files that have a .txt or .restext extension) or XML files (files that have a .resx extension). 然后,使用资源文件生成器(resgen.exe)编译文本或 XML 文件,以创建二进制 .resources 文件。You then compile the text or XML files with the Resource File Generator (Resgen.exe) to create a binary .resources file. 然后,可以通过使用编译器选项(如) /resources C#和 Visual Basic 编译器将生成的 .resources 文件嵌入到可执行文件或库中,也可以使用将其嵌入到附属程序集中。You can then embed the resulting .resources file in an executable or library by using a compiler option such as /resources for the C# and Visual Basic compilers, or you can embed it in a satellite assembly by using the . 如果你在 Visual Studio 项目中包含 .resx 文件,则 Visual Studio 将在生成过程中自动处理默认值和本地化资源的编译和嵌入。If you include a .resx file in your Visual Studio project, Visual Studio handles the compilation and embedding of default and localized resources automatically as part of the build process.

理想情况下,应为应用支持的每种语言创建资源,或至少为每种语言的有意义的子集创建资源。Ideally, you should create resources for every language your app supports, or at least for a meaningful subset of each language. 二进制 .resources 文件名称遵循命名约定basenamecultureName,其中basename是应用的名称或类的名称,具体取决于所需的详细程度。The binary .resources file names follow the naming convention basename.cultureName.resources, where basename is the name of the app or the name of a class, depending on the level of detail you want. 属性用于确定cultureName。 CultureInfo.NameThe CultureInfo.Name property is used to determine cultureName. 应用的默认区域性的资源应命名为basenameA resource for the app's default culture should be named basename.resources.

例如,假设程序集在资源文件中有多个资源,而该资源文件的基名称为 MyResources。For example, suppose that an assembly has several resources in a resource file that has the base name MyResources. 这些资源文件的名称应为日本(日本)区域性的 "MyResources"、"德语"、"MyResources"、"zh-chs"、"简体中文" 和 "MyResources" 等资源。MyResources.fr 法语(比利时)区域性的资源。These resource files should have names such as MyResources.ja-JP.resources for the Japan (Japanese) culture, MyResources.de.resources for the German culture, MyResources.zh-CHS.resources for the simplified Chinese culture, and MyResources.fr-BE.resources for the French (Belgium) culture. 默认的资源文件应命名为 MyResources。The default resource file should be named MyResources.resources. 区域性特定的资源文件通常打包在每个区域性的附属程序集中。The culture-specific resource files are commonly packaged in satellite assemblies for each culture. 默认资源文件应该嵌入应用程序的主程序集中。The default resource file should be embedded in the app's main assembly.

请注意,程序集链接器允许将资源标记为私有,但应始终将其标记为公共,以便其他程序集可以访问这些资源。Note that Assembly Linker allows resources to be marked as private, but you should always mark them as public so they can be accessed by other assemblies. (因为附属程序集不包含任何代码,所以标记为私有的资源对您的应用程序无法通过任何机制使用。)(Because a satellite assembly contains no code, resources that are marked as private are unavailable to your app through any mechanism.)

有关创建、打包和部署资源的详细信息,请参阅文章创建资源文件创建附属程序集以及打包和部署资源For more information about creating, packaging, and deploying resources, see the articles Creating Resource Files, Creating Satellite Assemblies, and Packaging and Deploying Resources.

实例化 ResourceManager 对象Instantiating a ResourceManager Object

可以实例化ResourceManager一个对象,该对象通过调用其类构造函数重载之一从嵌入的 .resources 文件中检索资源。You instantiate a ResourceManager object that retrieves resources from an embedded .resources file by calling one of its class constructor overloads. 这会将ResourceManager对象与特定 .resources 文件和附属程序集中任何关联的本地化 .resources 文件紧密耦合在一起。This tightly couples a ResourceManager object with a particular .resources file and with any associated localized .resources files in satellite assemblies.

最常调用的两个构造函数为:The two most commonly called constructors are:

  • ResourceManager(String, Assembly)基于您提供的两个信息段查找资源: .resources 文件的基名称和默认 .resources 文件所在的程序集。ResourceManager(String, Assembly) looks up resources based on two pieces of information that you supply: the base name of the .resources file, and the assembly in which the default .resources file resides. 基名称包含 .resources 文件的命名空间和根名称,而不包含其区域性或扩展名。The base name includes the namespace and root name of the .resources file, without its culture or extension. 请注意,从命令行编译的资源文件通常不包括命名空间名称,而在 Visual Studio 环境中创建的资源文件则执行此操作。Note that .resources files that are compiled from the command line typically do not include a namespace name, whereas .resources files that are created in the Visual Studio environment do. 例如,如果资源文件命名为 MyCompany,并且ResourceManager构造函数是从名为Example.Main的静态方法调用的,则下面的代码将实例化一个ResourceManager可以从中检索资源的对象。资源文件:For example, if a resource file is named MyCompany.StringResources.resources and the ResourceManager constructor is called from a static method named Example.Main, the following code instantiates a ResourceManager object that can retrieve resources from the .resources file:

    ResourceManager rm = new ResourceManager("MyCompany.StringResources", 
                                             typeof(Example).Assembly);
    
    Dim rm As New ResourceManager("MyCompany.StringResources",
                                  GetType(Example).Assembly)
    
  • ResourceManager(Type)基于类型对象中的信息在附属程序集内查找资源。ResourceManager(Type) looks up resources in satellite assemblies based on information from a type object. 该类型的完全限定名对应于 .resources 文件的基名称,而不包含其文件扩展名。The type's fully qualified name corresponds to the base name of the .resources file without its file name extension. 在使用 Visual Studio 资源设计器创建的桌面应用程序中,Visual Studio 会创建一个包装类,它的完全限定名与 .resources 文件的根名称相同。In desktop apps that are created by using the Visual Studio Resource Designer, Visual Studio creates a wrapper class whose fully qualified name is the same as the root name of the .resources file. 例如,如果资源文件命名为 MyCompany,并且有一个名为MyCompany.StringResources的包装器类,则以下代码将实例化一个ResourceManager可以从 .resources 文件中检索资源的对象:For example, if a resource file is named MyCompany.StringResources.resources and there is a wrapper class named MyCompany.StringResources, the following code instantiates a ResourceManager object that can retrieve resources from the .resources file:

    ResourceManager rm = new ResourceManager(typeof(MyCompany.StringResources));
    
    Dim rm As New ResourceManager(GetType(MyCompany.StringResources))
    

如果找不到合适的资源,则构造函数调用会创建ResourceManager一个有效的对象。If the appropriate resources cannot be found, the constructor call creates a valid ResourceManager object. 不过,尝试检索资源会引发MissingManifestResourceException异常。However, the attempt to retrieve a resource throws a MissingManifestResourceException exception. 有关处理异常的信息,请参阅本文后面的 "处理 MissingManifestResourceException 和 MissingSatelliteAssembly 异常" 一节。For information about dealing with the exception, see the Handling MissingManifestResourceException and MissingSatelliteAssembly Exceptions section later in this article.

下面的示例演示如何实例化ResourceManager对象。The following example shows how to instantiate a ResourceManager object. 它包含名为 ShowTime 的可执行文件的源代码。It contains the source code for an executable named ShowTime.exe. 它还包括以下名为 Strings 的文本文件, TimeHeader其中包含单个字符串资源:It also includes the following text file named Strings.txt that contains a single string resource, TimeHeader:

TimeHeader=The current time is  

可以使用批处理文件生成资源文件,并将其嵌入到可执行文件中。You can use a batch file to generate the resource file and embed it into the executable. 下面是使用C#编译器生成可执行文件的批处理文件:Here's the batch file to generate an executable by using the C# compiler:

  
resgen strings.txt  
csc ShowTime.cs /resource:strings.resources  
  

对于 Visual Basic 编译器,可以使用以下批处理文件:For the Visual Basic compiler, you can use the following batch file:

  
resgen strings.txt  
vbc ShowTime.vb /resource:strings.resources  
  
using System;
using System.Resources;

public class Example
{
   public static void Main()
   {
      ResourceManager rm = new ResourceManager("Strings", 
                               typeof(Example).Assembly);
      string timeString = rm.GetString("TimeHeader");
      Console.WriteLine("{0} {1:T}", timeString, DateTime.Now);   
   }
}
// The example displays output like the following:
//        The current time is 2:03:14 PM
Imports System.Resources

Module Example
   Public Sub Main()
      Dim rm As New ResourceManager("Strings", GetType(Example).Assembly)
      Dim timeString As String = rm.GetString("TimeHeader")
      Console.WriteLine("{0} {1:T}", timeString, Date.Now)   
   End Sub
End Module
' The example displays output similar to the following:
'       The current time is 2:03:14 PM

ResourceManager 和特定于区域性的资源ResourceManager and Culture-Specific Resources

本地化应用需要部署资源,如打包和部署资源一文中所述。A localized app requires resources to be deployed, as discussed in the article Packaging and Deploying Resources. 如果正确配置了程序集,则资源管理器会根据当前线程的Thread.CurrentUICulture属性来确定要检索的资源。If the assemblies are properly configured, the resource manager determines which resources to retrieve based on the current thread's Thread.CurrentUICulture property. (该属性还返回当前线程的 UI 区域性。)例如,如果某个应用使用主程序集中的默认英语资源进行编译,并且在两个附属程序集中使用法语和俄语语言资源,并且该Thread.CurrentUICulture属性设置为 fr-fr,则资源管理器将检索法语中心.(That property also returns the current thread's UI culture.) For example, if an app is compiled with default English language resources in the main assembly and with French and Russian language resources in two satellite assemblies, and the Thread.CurrentUICulture property is set to fr-FR, the resource manager retrieves the French resources.

可以显式或隐CurrentUICulture式设置属性。You can set the CurrentUICulture property explicitly or implicitly. 设置此方法的方式决定了ResourceManager对象如何根据区域性检索资源:The way you set it determines how the ResourceManager object retrieves resources based on culture:

  • 如果将Thread.CurrentUICulture属性显式设置为特定区域性,则资源管理器始终会检索该区域性的资源,而不考虑用户的浏览器或操作系统语言。If you explicitly set the Thread.CurrentUICulture property to a specific culture, the resource manager always retrieves the resources for that culture, regardless of the user's browser or operating system language. 假设某个应用使用默认的英语资源和三个附属程序集进行编译,其中包含英语(美国)、法语(法国)和俄语(俄罗斯)的资源。Consider an app that is compiled with default English language resources and three satellite assemblies that contain resources for English (United States), French (France), and Russian (Russia). 如果将ResourceManager属性设置为 fr-fr,则对象将始终检索法语(法国)资源,即使用户的操作系统语言不是法语。 CurrentUICultureIf the CurrentUICulture property is set to fr-FR, the ResourceManager object always retrieves the French (France) resources, even if the user's operating system language is not French. 在显式设置属性之前,请确保这是所需的行为。Make sure that this is the desired behavior before you set the property explicitly.

    在 ASP.NET apps 中,必须显式设置Thread.CurrentUICulture属性,因为服务器上的设置可能不会与传入的客户端请求匹配。In ASP.NET apps, you must set the Thread.CurrentUICulture property explicitly, because it is unlikely that the setting on the server will match incoming client requests. ASP.NET 应用可以将Thread.CurrentUICulture属性显式设置为用户的浏览器接受语言。An ASP.NET app can set the Thread.CurrentUICulture property explicitly to the user's browser accept language.

    显式设置Thread.CurrentUICulture属性可定义该线程的当前 UI 区域性。Explicitly setting the Thread.CurrentUICulture property defines the current UI culture for that thread. 它不会影响应用程序中任何其他线程的当前 UI 区域性。It does not affect the current UI culture of any other threads in an app.

  • 可以通过将表示区域性的CultureInfo对象分配给静态CultureInfo.DefaultThreadCurrentUICulture属性,来设置应用程序域中所有线程的 UI 区域性。You can set the UI culture of all threads in an app domain by assigning a CultureInfo object that represents that culture to the static CultureInfo.DefaultThreadCurrentUICulture property.

  • 如果未显式设置当前 UI 区域性并且未定义当前应用程序域的默认区域性,则 Windows CultureInfo.CurrentUICulture GetUserDefaultUILanguage函数将隐式设置该属性。If you do not explicitly set the current UI culture and you do not define a default culture for the current app domain, the CultureInfo.CurrentUICulture property is set implicitly by the Windows GetUserDefaultUILanguage function. 此函数由多语言用户界面(MUI)提供,使用户能够设置默认语言。This function is provided by the Multilingual User Interface (MUI), which enables the user to set the default language. 如果用户未设置 UI 语言,则默认为系统安装的语言,这是操作系统资源的语言。If the UI language is not set by the user, it defaults to the system-installed language, which is the language of operating system resources.

以下简单的 "Hello world" 示例显式设置了当前 UI 区域性。The following simple "Hello world" example sets the current UI culture explicitly. 它包含三个区域性的资源:英语(美国)或 en-us、法语(法国)或 fr-fr、俄语(俄罗斯)或 ru。It contains resources for three cultures: English (United States) or en-US, French (France) or fr-FR, and Russian (Russia) or ru-RU. En-us 资源包含在名为 "问候" 的文本文件中:The en-US resources are contained in a text file named Greetings.txt:

HelloString=Hello world!  

Fr-fr 资源包含在名为 Greetings.fr-FR.TXT 的文本文件中:The fr-FR resources are contained in a text file named Greetings.fr-FR.txt:

HelloString=Salut tout le monde!  

Ru-RU 资源包含在名为 Greetings.ru-RU.TXT 的文本文件中:The ru-RU resources are contained in a text file named Greetings.ru-RU.txt:

HelloString=Всем привет!  

下面是此示例的源代码(示例 .vb 适用于该C#版本的 Visual Basic 版本或 Example.cs):Here's the source code for the example (Example.vb for the Visual Basic version or Example.cs for the C# version):

using System;
using System.Globalization;
using System.Resources;
using System.Threading;

public class Example
{
   public static void Main()
   {
      // Create array of supported cultures
      string[] cultures = {"en-CA", "en-US", "fr-FR", "ru-RU" };
      Random rnd = new Random();
      int cultureNdx = rnd.Next(0, cultures.Length);
      CultureInfo originalCulture = Thread.CurrentThread.CurrentCulture;
      ResourceManager rm = new ResourceManager("Greetings", typeof(Example).Assembly);
      try {
         CultureInfo newCulture = new CultureInfo(cultures[cultureNdx]);
         Thread.CurrentThread.CurrentCulture = newCulture;
         Thread.CurrentThread.CurrentUICulture = newCulture;
         string greeting = String.Format("The current culture is {0}.\n{1}",
                                         Thread.CurrentThread.CurrentUICulture.Name,
                                         rm.GetString("HelloString"));
         Console.WriteLine(greeting);
      }
      catch (CultureNotFoundException e) {
         Console.WriteLine("Unable to instantiate culture {0}", e.InvalidCultureName);
      }
      finally {
         Thread.CurrentThread.CurrentCulture = originalCulture;
         Thread.CurrentThread.CurrentUICulture = originalCulture;
      }
   }
}
// The example displays output like the following:
//       The current culture is ru-RU.
//       Всем привет!
Imports System.Globalization
Imports System.Resources
Imports System.Threading

Module Example
   Sub Main()
      ' Create array of supported cultures
      Dim cultures() As String = {"en-CA", "en-US", "fr-FR", "ru-RU" }
      Dim rnd As New Random()
      Dim cultureNdx As Integer = rnd.Next(0, cultures.Length)
      Dim originalCulture As CultureInfo = Thread.CurrentThread.CurrentCulture
      Dim rm As New ResourceManager("Greetings", GetType(Example).Assembly)
      Try
         Dim newCulture As New CultureInfo(cultures(cultureNdx))
         Thread.CurrentThread.CurrentCulture = newCulture
         Thread.CurrentThread.CurrentUICulture = newCulture
         Dim greeting As String = String.Format("The current culture is {0}.{1}{2}",
                                                Thread.CurrentThread.CurrentUICulture.Name,
                                                vbCrLf, rm.GetString("HelloString"))

         Console.WriteLine(greeting)
      Catch e As CultureNotFoundException
         Console.WriteLine("Unable to instantiate culture {0}", e.InvalidCultureName)
      Finally
         Thread.CurrentThread.CurrentCulture = originalCulture
         Thread.CurrentThread.CurrentUICulture = originalCulture
      End Try
   End Sub
End Module
' The example displays output like the following:
'       The current culture is ru-RU.
'       Всем привет!

若要编译此示例,请创建一个包含以下命令的批处理(.bat)文件,并从命令提示符运行该文件。To compile this example, create a batch (.bat) file that contains the following commands and run it from the command prompt. C#如果使用的是,请csc指定而vbcExample.cs是和Example.vb而不是。If you're using C#, specify csc instead of vbc and Example.cs instead of Example.vb.

resgen Greetings.txt   
vbc Example.vb /resource:Greetings.resources  
  
resgen Greetings.fr-FR.txt  
Md fr-FR  
al /embed:Greetings.fr-FR.resources /culture:fr-FR /out:fr-FR\Example.resources.dll  
  
resgen Greetings.ru-RU.txt  
Md ru-RU  
al /embed:Greetings.ru-RU.resources /culture:ru-RU /out:ru-RU\Example.resources.dll  

检索资源Retrieving Resources

调用GetObject(String)GetString(String)方法来访问特定资源。You call the GetObject(String) and GetString(String) methods to access a specific resource. 还可以调用GetStream(String)方法以将非字符串资源作为字节数组来检索。You can also call the GetStream(String) method to retrieve non-string resources as a byte array. 默认情况下,在已本地化资源的应用程序中,这些方法返回由进行调用的线程的当前 UI 区域性确定的区域性的资源。By default, in an app that has localized resources, these methods return the resource for the culture determined by the current UI culture of the thread that made the call. 有关如何定义线程的当前 UI 区域性的详细信息,请参阅上一节: ResourceManager 和特定于区域性的资源See the previous section, ResourceManager and Culture-Specific Resources, for more information about how the current UI culture of a thread is defined. 如果资源管理器找不到当前线程的 UI 区域性的资源,它将使用回退进程来检索指定的资源。If the resource manager cannot find the resource for the current thread's UI culture, it uses a fallback process to retrieve the specified resource. 如果资源管理器找不到任何已本地化的资源,它将使用默认区域性的资源。If the resource manager cannot find any localized resources, it uses the resources of the default culture. 有关资源回退规则的详细信息,请参阅打包和部署资源一文中的 "资源回退进程" 一节。For more information about resource fallback rules, see the "Resource Fallback Process" section of the article Packaging and Deploying Resources.

备注

如果找不到ResourceManager类构造函数中指定的 .resources 文件,尝试检索资源会MissingManifestResourceException引发或MissingSatelliteAssemblyException异常。If the .resources file specified in the ResourceManager class constructor cannot be found, the attempt to retrieve a resource throws a MissingManifestResourceException or MissingSatelliteAssemblyException exception. 有关处理异常的信息,请参阅本主题后面的 "处理 MissingManifestResourceException 和 MissingSatelliteAssemblyException 异常" 一节。For information about dealing with the exception, see the Handling MissingManifestResourceException and MissingSatelliteAssemblyException Exceptions section later in this topic.

下面的示例使用GetString方法检索特定于区域性的资源。The following example uses the GetString method to retrieve culture-specific resources. 它包含从 .txt 文件中编译的、英语(en)、法语(法国)(fr)和俄语(俄罗斯)(ru)区域性的资源。It consists of resources compiled from .txt files for the English (en), French (France) (fr-FR), and Russian (Russia) (ru-RU) cultures. 该示例将当前区域性和当前 UI 区域性更改为英语(美国)、法语(法国)、俄语(俄罗斯)和瑞典语(瑞典)。The example changes the current culture and current UI culture to English (United States), French (France), Russian (Russia), and Swedish (Sweden). 然后,它调用GetString方法来检索本地化字符串,该字符串与当前日期和月份一起显示。It then calls the GetString method to retrieve the localized string, which it displays along with the current day and month. 请注意,输出将显示适当的本地化字符串,除非当前 UI 区域性为 "瑞典语(瑞典)"。Notice that the output displays the appropriate localized string except when the current UI culture is Swedish (Sweden). 由于瑞典语资源不可用,因此应用会改用默认区域性的资源,即英语。Because Swedish language resources are unavailable, the app instead uses the resources of the default culture, which is English.

该示例需要下表中列出的基于文本的资源文件。The example requires the text-based resource files listed in following table. 每个都有一个名为DateStart的字符串资源。Each has a single string resource named DateStart.

cultureCulture 文件名File name 资源名称Resource name 资源值Resource value
en-USen-US DateStrings.txtDateStrings.txt DateStart 今天是Today is
fr-FRfr-FR DateStrings.fr-FR.txtDateStrings.fr-FR.txt DateStart Aujourd'hui,c'est leAujourd'hui, c'est le
ru-RUru-RU DateStrings.ru-RU.txtDateStrings.ru-RU.txt DateStart СегодняСегодня

下面是示例的源代码(适用于 Visual Basic 版本的 ShowDate 或代码C#版本的 ShowDate.cs)。Here's the source code for the example (ShowDate.vb for the Visual Basic version or ShowDate.cs for the C# version of the code).

using System;
using System.Globalization;
using System.Resources;
using System.Threading;

[assembly:NeutralResourcesLanguage("en")]

public class Example
{
   public static void Main()
   {
      string[] cultureNames = { "en-US", "fr-FR", "ru-RU", "sv-SE" };
      ResourceManager rm = new ResourceManager("DateStrings",
                                               typeof(Example).Assembly);
      
      foreach (var cultureName in cultureNames) {
         CultureInfo culture = CultureInfo.CreateSpecificCulture(cultureName);
         Thread.CurrentThread.CurrentCulture = culture; 
         Thread.CurrentThread.CurrentUICulture = culture;

         Console.WriteLine("Current UI Culture: {0}", 
                           CultureInfo.CurrentUICulture.Name);
         string dateString = rm.GetString("DateStart");
         Console.WriteLine("{0} {1:M}.\n", dateString, DateTime.Now);                           
      }                                           
   }
}
// The example displays output similar to the following:
//       Current UI Culture: en-US
//       Today is February 03.
//       
//       Current UI Culture: fr-FR
//       Aujourd'hui, c'est le 3 février
//       
//       Current UI Culture: ru-RU
//       Сегодня февраля 03.
//       
//       Current UI Culture: sv-SE
//       Today is den 3 februari.
Imports System.Globalization
Imports System.Resources
Imports System.Threading

<Assembly:NeutralResourcesLanguage("en")>

Module Example
   Public Sub Main()
      Dim cultureNames() As String = { "en-US", "fr-FR", "ru-RU", "sv-SE" }
      Dim rm As New ResourceManager("DateStrings",
                                    GetType(Example).Assembly)
      
      For Each cultureName In cultureNames
         Dim culture As CultureInfo = CultureInfo.CreateSpecificCulture(cultureName)
         Thread.CurrentThread.CurrentCulture = culture 
         Thread.CurrentThread.CurrentUICulture = culture

         Console.WriteLine("Current UI Culture: {0}", 
                           CultureInfo.CurrentUICulture.Name)
         Dim dateString As String = rm.GetString("DateStart")
         Console.WriteLine("{0} {1:M}.", dateString, Date.Now)                           
         Console.WriteLine()
      Next                                           
   End Sub
End Module
' The example displays output similar to the following:
'       Current UI Culture: en-US
'       Today is February 03.
'       
'       Current UI Culture: fr-FR
'       Aujourd'hui, c'est le 3 février
'       
'       Current UI Culture: ru-RU
'       Сегодня февраля 03.
'       
'       Current UI Culture: sv-SE
'       Today is den 3 februari.

若要编译此示例,请创建一个包含以下命令的批处理文件,并从命令提示符运行该文件。To compile this example, create a batch file that contains the following commands and run it from the command prompt. C#如果使用的是,请csc指定而vbcshowdate.cs是和showdate.vb而不是。If you're using C#, specify csc instead of vbc and showdate.cs instead of showdate.vb.

  
resgen DateStrings.txt  
vbc showdate.vb /resource:DateStrings.resources  
  
md fr-FR  
resgen DateStrings.fr-FR.txt  
al /out:fr-FR\Showdate.resources.dll /culture:fr-FR /embed:DateStrings.fr-FR.resources   
  
md ru-RU  
resgen DateStrings.ru-RU.txt  
al /out:ru-RU\Showdate.resources.dll /culture:ru-RU /embed:DateStrings.ru-RU.resources  
  

可以通过两种方法来检索当前 UI 区域性以外的特定区域性的资源:There are two ways to retrieve the resources of a specific culture other than the current UI culture:

  • 可以调用GetString(String, CultureInfo)GetObject(String, CultureInfo)GetStream(String, CultureInfo)方法来检索特定区域性的资源。You can call the GetString(String, CultureInfo), GetObject(String, CultureInfo), or GetStream(String, CultureInfo) method to retrieve a resource for a specific culture. 如果找不到本地化的资源,资源管理器将使用资源回退进程来查找适当的资源。If a localized resource cannot be found, the resource manager uses the resource fallback process to locate an appropriate resource.

  • 可以调用GetResourceSet方法来ResourceSet获取表示特定区域性的资源的对象。You can call the GetResourceSet method to obtain a ResourceSet object that represents the resources for a particular culture. 在方法调用中,如果资源管理器找不到已本地化的资源,或者是否只是回退到默认区域性的资源,则可以确定资源管理器是否对父区域性进行探测。In the method call, you can determine whether the resource manager probes for parent cultures if it is unable to find localized resources, or whether it simply falls back to the resources of the default culture. 然后,可以使用这些ResourceSet方法通过名称访问资源(针对该区域性进行了本地化)或枚举集中的资源。You can then use the ResourceSet methods to access the resources (localized for that culture) by name, or to enumerate the resources in the set.

处理 MissingManifestResourceException 和 MissingSatelliteAssemblyException 异常Handling MissingManifestResourceException and MissingSatelliteAssemblyException Exceptions

如果尝试检索特定资源,但资源管理器找不到该资源,或者未定义默认区域性,或者无法定位默认区域性的资源,则资源管理器将引发MissingManifestResourceException异常。MissingSatelliteAssemblyException如果需要在附属程序集中查找资源,则应查找主程序集中的资源或。If you try to retrieve a specific resource, but the resource manager cannot find that resource and either no default culture has been defined or the resources of the default culture cannot be located, the resource manager throws a MissingManifestResourceException exception if it expects to find the resources in the main assembly or a MissingSatelliteAssemblyException if it expects to find the resources in a satellite assembly. 请注意,当您调用资源检索方法(如GetStringGetObject),而ResourceManager不是实例化对象时,将引发异常。Note that the exception is thrown when you call a resource retrieval method such as GetString or GetObject, and not when you instantiate a ResourceManager object.

通常,在下列情况下会引发异常:The exception is typically thrown under the following conditions:

  • 适当的资源文件或附属程序集不存在。The appropriate resource file or satellite assembly does not exist. 如果资源管理器希望在主应用程序集中嵌入应用的默认资源,则这些资源不存在。If the resource manager expects the app's default resources to be embedded in the main app assembly, they are absent. 如果该NeutralResourcesLanguageAttribute特性指示应用程序的默认资源位于附属程序集中,则找不到该程序集。If the NeutralResourcesLanguageAttribute attribute indicates that the app's default resources reside in a satellite assembly, that assembly cannot be found. 在编译应用程序时,请确保将资源嵌入到主程序集中,或者生成必要的附属程序集并正确命名。When you compile your app, make sure that resources are embedded in the main assembly or that the necessary satellite assembly is generated and is named appropriately. 其名称应采用appName. .resources 格式,并应位于以其所包含资源的区域性命名的目录中。Its name should take the form appName.resources.dll, and it should be located in a directory named after the culture whose resources it contains.

  • 应用未定义默认或非特定区域性。Your app doesn't have a default or neutral culture defined. 将特性添加到源代码文件或项目信息文件(AssemblyInfo 应用程序的 Visual Basic 或C#应用程序的 AssemblyInfo.cs)文件。 NeutralResourcesLanguageAttributeAdd the NeutralResourcesLanguageAttribute attribute to a source code file or to the project information file (AssemblyInfo.vb for a Visual Basic app or AssemblyInfo.cs for a C# app) file.

  • 构造ResourceManager(String, Assembly)函数中的baseName参数未指定 .resources 文件的名称。The baseName parameter in the ResourceManager(String, Assembly) constructor does not specify the name of a .resources file. 名称应包括资源文件的完全限定命名空间,但不包括其文件扩展名。The name should include the resource file's fully qualified namespace but not its file name extension. 通常,在 Visual Studio 中创建的资源文件包含命名空间名称,但是在命令提示符处创建和编译的资源文件不会包含在内。Typically, resource files that are created in Visual Studio include namespace names, but resource files that are created and compiled at the command prompt do not. 可以通过编译并运行以下实用工具来确定嵌入 .resources 文件的名称。You can determine the names of embedded .resources files by compiling and running the following utility. 这是一个控制台应用,它接受主程序集或附属程序集的名称作为命令行参数。This is a console app that accepts the name of a main assembly or satellite assembly as a command-line parameter. 它显示应作为baseName参数提供的字符串,以便资源管理器可以正确地识别资源。It displays the strings that should be provided as the baseName parameter so that the resource manager can correctly identify the resource.

    using System;
    using System.IO;
    using System.Reflection;
    using System.Resources;
    
    public class Example
    {
       public static void Main()
       {
          if (Environment.GetCommandLineArgs().Length == 1) { 
             Console.WriteLine("No filename.");
             return;
          }
          
          string filename = Environment.GetCommandLineArgs()[1].Trim();
          // Check whether the file exists.
          if (! File.Exists(filename)) {
             Console.WriteLine("{0} does not exist.", filename);
             return;
          }   
          
          // Try to load the assembly.
          Assembly assem = Assembly.LoadFrom(filename);
          Console.WriteLine("File: {0}", filename);
             
          // Enumerate the resource files.
          string[] resNames = assem.GetManifestResourceNames();
          if (resNames.Length == 0)
             Console.WriteLine("   No resources found.");
    
          foreach (var resName in resNames)
             Console.WriteLine("   Resource: {0}", resName.Replace(".resources", ""));
    
          Console.WriteLine();
       }
    }
    
    Imports System.IO
    Imports System.Reflection
    Imports System.Resources
    
    Module Example
       Public Sub Main()
          If Environment.GetCommandLineArgs.Length = 1 Then 
             Console.WriteLine("No filename.")
             Exit Sub
          End If
          Dim filename As String = Environment.GetCommandLineArgs(1).Trim()
          ' Check whether the file exists.
          If Not File.Exists(filename) Then
             Console.WriteLine("{0} does not exist.", filename)
             Exit Sub
          End If   
          
          ' Try to load the assembly.
          Dim assem As Assembly = Assembly.LoadFrom(filename)
          Console.WriteLine("File: {0}", filename)
             
          ' Enumerate the resource files.
          Dim resNames() As String = assem.GetManifestResourceNames()
          If resNames.Length = 0 Then
             Console.WriteLine("   No resources found.")
          End If
          For Each resName In resNames
             Console.WriteLine("   Resource: {0}", resName.Replace(".resources", ""))
          Next
          Console.WriteLine()
       End Sub
    End Module
    

如果要显式更改应用程序的当前区域性,还应记住,资源管理器将基于CultureInfo.CurrentUICulture属性的值而CultureInfo.CurrentCulture不是属性来检索资源集。If you are changing the current culture of your application explicitly, you should also remember that the resource manager retrieves a resource set based on the value of the CultureInfo.CurrentUICulture property, and not the CultureInfo.CurrentCulture property. 通常情况下,如果更改一个值,则还应更改另一个值。Typically, if you change one value, you should also change the other.

资源版本控制Resource Versioning

由于包含应用的默认资源的主程序集是独立于应用程序的附属程序集,因此,您可以在不重新部署附属程序集的情况下发布主程序集的新版本。Because the main assembly that contains an app's default resources is separate from the app's satellite assemblies, you can release a new version of your main assembly without redeploying the satellite assemblies. 使用SatelliteContractVersionAttribute特性可使用现有附属程序集,并指示资源管理器不要使用新版本的主程序集重新部署它们。You use the SatelliteContractVersionAttribute attribute to use existing satellite assemblies and instruct the resource manager not to redeploy them with a new version of your main assembly,

有关对附属程序集的版本控制支持的详细信息,请参阅文章检索资源For more information about versioning support for satellite assemblies, see the article Retrieving Resources.

<satelliteassemblies > 配置文件节点<satelliteassemblies> Configuration File Node

对于从网站(HREF 文件)部署和运行的可执行文件,该ResourceManager对象可能会通过 web 探测附属程序集,这可能会损害应用程序的性能。For executables that are deployed and run from a website (HREF .exe files), the ResourceManager object may probe for satellite assemblies over the web, which can hurt your app's performance. 若要消除性能问题,可以将此探测范围限制为已与应用一起部署的附属程序集。To eliminate the performance problem, you can limit this probing to the satellite assemblies that you have deployed with your app. 为此,请在应用程序<satelliteassemblies>的配置文件中创建一个节点,以指定已为应用程序部署了一组特定的区域性,并且ResourceManager该对象不应尝试探测该节点中未列出的任何区域性。To do this, you create a <satelliteassemblies> node in your app's configuration file to specify that you have deployed a specific set of cultures for your app, and that the ResourceManager object should not try to probe for any culture that is not listed in that node.

备注

创建<satelliteassemblies>节点的首选替代方法是使用ClickOnce 部署清单功能。The preferred alternative to creating a <satelliteassemblies> node is to use the ClickOnce Deployment Manifest feature.

在应用的配置文件中,创建如下所示的部分:In your app's configuration file, create a section similar to the following:

<?xml version ="1.0"?>  
<configuration>  
    <satelliteassemblies>  
        <assembly name="MainAssemblyName, Version=versionNumber, Culture=neutral, PublicKeyToken=null|yourPublicKeyToken">  
            <culture>cultureName1</culture>  
            <culture>cultureName2</culture>  
            <culture>cultureName3</culture>  
        </assembly>  
    </satelliteassemblies>  
</configuration>  

按如下所示编辑此配置信息:Edit this configuration information as follows:

  • 为部署的每<assembly>个主程序集指定一个或多个节点,其中每个节点指定完全限定的程序集名称。Specify one or more <assembly> nodes for each main assembly that you deploy, where each node specifies a fully qualified assembly name. 指定主程序集的名称代替MainAssemblyName,并指定VersionPublicKeyTokenCulture属性值,这些值对应于主程序集。Specify the name of your main assembly in place of MainAssemblyName, and specify the Version, PublicKeyToken, and Culture attribute values that correspond to your main assembly.

    对于 " Version属性",请指定程序集的版本号。For the Version attribute, specify the version number of your assembly. 例如,程序集的第一个版本可能是版本号1.0.0.0。For example, the first release of your assembly might be version number 1.0.0.0.

    对于属性,如果尚未使用强null名称对程序集进行签名,则指定关键字; 如果已对程序集进行签名,则指定公钥标记。 PublicKeyTokenFor the PublicKeyToken attribute, specify the keyword null if you have not signed your assembly with a strong name, or specify your public key token if you have signed your assembly.

    对于特性,指定关键字neutral以指定ResourceManager主程序集,并使类只对<culture>节点中列出的区域性进行探测。 CultureFor the Culture attribute, specify the keyword neutral to designate the main assembly and cause the ResourceManager class to probe only for the cultures listed in the <culture> nodes.

    有关完全限定的程序集名称的详细信息,请参阅程序集名称一文。For more information about fully qualified assembly names, see the article Assembly Names. 有关强名称程序集的详细信息,请参阅创建和使用具有强名称的程序集一文。For more information about strong-named assemblies, see the article Creating and Using Strong-Named Assemblies.

  • 指定一个或多<culture>个具有特定区域性名称(如 "fr")或非特定区域性名称(如 "fr")的节点。Specify one or more <culture> nodes with a specific culture name, such as "fr-FR", or a neutral culture name, such as "fr".

如果<satelliteassemblies>节点中未列出的任何程序集需要资源,则ResourceManager该类使用标准探测规则探测区域性。If resources are needed for any assembly not listed under the <satelliteassemblies> node, the ResourceManager class probes for cultures using standard probing rules.

Windows 8.x 应用商店Windows 8.x Store 应用程序Apps

重要

尽管此ResourceManager类在应用中Windows 8.x 应用商店Windows 8.x Store受支持,但我们不建议使用它。Although the ResourceManager class is supported in Windows 8.x 应用商店Windows 8.x Store apps, we do not recommend its use. 仅当你开发可移植类库Portable Class LibraryWindows 8.x 应用商店Windows 8.x Store用于应用程序的项目时,才使用此类。Use this class only when you develop 可移植类库Portable Class Library projects that can be used with Windows 8.x 应用商店Windows 8.x Store apps. 若要从Windows 8.x 应用商店Windows 8.x Store应用中检索资源,请改用windows.applicationmodel.resources.core. windows.applicationmodel.resources.resourceloader类。To retrieve resources from Windows 8.x 应用商店Windows 8.x Store apps, use the Windows.ApplicationModel.Resources.ResourceLoader class instead.

对于Windows 8.x 应用商店Windows 8.x Store 应用ResourceManager ,类从包资源索引(PRI)文件中检索资源。For Windows 8.x 应用商店Windows 8.x Store apps, the ResourceManager class retrieves resources from package resource index (PRI) files. 单个 PRI 文件(应用程序包 PRI 文件)包含默认区域性和任何已本地化的区域性的资源。A single PRI file (the application package PRI file) contains the resources for both the default culture and any localized cultures. 使用 Makepri.exe 实用工具,可以从一个或多个 XML 资源文件(.resw)格式创建 PRI 文件。You use the MakePRI utility to create a PRI file from one or more resource files that are in XML resource (.resw) format. 对于包含在 Visual Studio 项目中的资源,Visual Studio 会自动处理创建和打包 PRI 文件的过程。For resources that are included in a Visual Studio project, Visual Studio handles the process of creating and packaging the PRI file automatically. 然后,可以使用 .NET Framework ResourceManager类访问应用程序或库的资源。You can then use the .NET Framework ResourceManager class to access the app's or library's resources.

可以采用与桌面ResourceManager应用相同的Windows 8.x 应用商店Windows 8.x Store方式来实例化应用程序的对象。You can instantiate a ResourceManager object for a Windows 8.x 应用商店Windows 8.x Store app in the same way that you do for a desktop app.

然后,你可以通过传递要检索到GetString(String)方法的资源的名称,来访问特定区域性的资源。You can then access the resources for a particular culture by passing the name of the resource to be retrieved to the GetString(String) method. 默认情况下,此方法返回由进行调用的线程的当前 UI 区域性确定的区域性的资源。By default, this method returns the resource for the culture determined by the current UI culture of the thread that made the call. 你还可以通过传递资源的名称和CultureInfo表示其资源要检索GetString(String, CultureInfo)到方法的区域性的对象来检索特定区域性的资源。You can also retrieve the resources for a specific culture by passing the name of the resource and a CultureInfo object that represents the culture whose resource is to be retrieved to the GetString(String, CultureInfo) method. 如果找不到当前 UI 区域性或指定区域性的资源,资源管理器将使用 UI 语言回退列表定位合适的资源。If the resource for the current UI culture or the specified culture cannot be found, the resource manager uses a UI language fallback list to locate a suitable resource.

构造函数

ResourceManager()

使用默认值初始化 ResourceManager 类的新实例。Initializes a new instance of the ResourceManager class with default values.

ResourceManager(String, Assembly)

初始化 ResourceManager 类的新实例,该实例在给定的程序集中查找从指定根名称导出的文件中包含的资源。Initializes a new instance of the ResourceManager class that looks up resources contained in files with the specified root name in the given assembly.

ResourceManager(String, Assembly, Type)

初始化使用指定 ResourceSetResourceManager 类的新实例,该实例在给定的程序集中的指定根名称类的文件中查找资源。Initializes a new instance of the ResourceManager class that uses a specified ResourceSet class to look up resources contained in files with the specified root name in the given assembly.

ResourceManager(Type)

它根据指定的对象中的信息在附属程序集内查找资源来初始化 ResourceManager 类的新实例。Initializes a new instance of the ResourceManager class that looks up resources in satellite assemblies based on information from the specified type object.

字段

BaseNameField

指定 ResourceManager 在其中搜索资源的资源文件的根名称。Specifies the root name of the resource files that the ResourceManager searches for resources.

HeaderVersionNumber

指定 ResourceManager 的当前实现可解释和产生的资源文件头的版本。Specifies the version of resource file headers that the current implementation of ResourceManager can interpret and produce.

MagicNumber

保留用于标识资源文件的数字。Holds the number used to identify resource files.

MainAssembly

指定包含资源的主要程序集。Specifies the main assembly that contains the resources.

ResourceSets

包含 Hashtable,它返回从区域性到 ResourceSet 对象的映射。Contains a Hashtable that returns a mapping from cultures to ResourceSet objects.

属性

BaseName

获取 ResourceManager 从其中搜索资源的资源文件的根名称。Gets the root name of the resource files that the ResourceManager searches for resources.

FallbackLocation

获取或设置检索默认回退资源的位置。Gets or sets the location from which to retrieve default fallback resources.

IgnoreCase

获取或设置值,该值指示资源管理器是否允许在 GetString(String)GetObject(String) 方法中进行不区分大小写的资源查找。Gets or sets a value that indicates whether the resource manager allows case-insensitive resource lookups in the GetString(String) and GetObject(String) methods.

ResourceSetType

获取资源管理器使用构造 ResourceSet 对象的资源设置对象的类型。Gets the type of the resource set object that the resource manager uses to construct a ResourceSet object.

方法

CreateFileBasedResourceManager(String, String, Type)

返回一个 ResourceManager 对象,它在特定的目录中而不在资源的程序集清单。Returns a ResourceManager object that searches a specific directory instead of an assembly manifest for resources.

Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetNeutralResourcesLanguage(Assembly)

通过检索指定程序及上的 NeutralResourcesLanguageAttribute 特性为主程序集的默认资源返回区域性特定的信息。Returns culture-specific information for the main assembly's default resources by retrieving the value of the NeutralResourcesLanguageAttribute attribute on a specified assembly.

GetObject(String)

返回指定的非字符串资源的值。Returns the value of the specified non-string resource.

GetObject(String, CultureInfo)

获取为指定区域性本地化的指定非字符串资源的值。Gets the value of the specified non-string resource localized for the specified culture.

GetResourceFileName(CultureInfo)

生成给定的 CultureInfo 对象的资源文件的名称。Generates the name of the resource file for the given CultureInfo object.

GetResourceSet(CultureInfo, Boolean, Boolean)

检索特定区域性的资源集合。Retrieves the resource set for a particular culture.

GetSatelliteContractVersion(Assembly)

返回给定程序集中的 SatelliteContractVersionAttribute 特性指定的版本。Returns the version specified by the SatelliteContractVersionAttribute attribute in the given assembly.

GetStream(String)

从指定资源返回非托管内存流对象。Returns an unmanaged memory stream object from the specified resource.

GetStream(String, CultureInfo)

使用指定的区域性从指定的资源返回非托管内存流对象。Returns an unmanaged memory stream object from the specified resource, using the specified culture.

GetString(String)

返回指定的字符串资源的值。Returns the value of the specified string resource.

GetString(String, CultureInfo)

返回为指定区域性本地化的字符串资源的值。Returns the value of the string resource localized for the specified culture.

GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
InternalGetResourceSet(CultureInfo, Boolean, Boolean)

提供用于查找资源集的实现。Provides the implementation for finding a resource set.

MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
ReleaseAllResources()

告知资源管理对所有 ResourceSet 对象调用方法 Close(),并释放所有资源。Tells the resource manager to call the Close() method on all ResourceSet objects and release all resources.

ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(继承自 Object)

适用于

线程安全性

此类型是线程安全的。This type is thread safe.

另请参阅