ResourceManager 類別

定義

表示在執行階段提供特定文化特性資源存取權限的資源管理員。Represents a resource manager that provides convenient access to culture-specific resources at run time.

public ref class ResourceManager
public class ResourceManager
[System.Serializable]
public class ResourceManager
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class ResourceManager
type ResourceManager = class
[<System.Serializable>]
type ResourceManager = class
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
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.txt 的檔案,其中包含下列資源字串: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.txt 輸入檔產生 rmc .resources 資源檔,如下所示: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. 在包含下列資源字串的 es MX 目錄中,建立名為 rmc.es-MX.txt 的檔案: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.txt 輸入檔產生 rmc.es MX .resources 資源檔,如下所示: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 .vb 或 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.resources.dll 附屬元件名稱。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. 如果 es-MX 是目前的目錄,請使用此命令: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.exe以獲取並顯示嵌入的資源字符串。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 儲存應用程式,請參閱下列各節:For more information about creating and managing resources in desktop apps and 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 物件,藉由呼叫方法,直接從不在元件中內嵌的 .resources 檔案取得資源。 CreateFileBasedResourceManagerYou 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 部署,因為這些資源會保持鎖定,直到方法明確釋放這些資源為止 ReleaseAllResourcesUsing 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 apps 來部署資源,您應該將 .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-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.dll。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 或副檔名) 或副檔名為) .resx 的 XML 檔案 (檔。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. 然後,您可以使用編譯器選項(例如 c # 和 Visual Basic 編譯器)將產生的 .resources 檔案內嵌在可執行檔或程式庫中 /resources ,也可以使用 元件連結器 (AI.exe) 將它內嵌在附屬元件中。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 Assembly Linker (AI.exe). 如果您在 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. CultureInfo.Name屬性是用來決定 cultureNameThe 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、德國文化特性的、MyResources. zh-CHS、簡體中文文化特性的資源,以及 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. 請注意,從命令列編譯的 .resources 檔案通常不會包含命名空間名稱,而在 Visual Studio 環境中建立的 .resources 檔案也不包含命名空間名稱。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 StringResources,而該函式 ResourceManager 是從名為的靜態方法呼叫 Example.Main ,則下列程式碼會具現化 ResourceManager 可從 .resources 檔案取出資源的物件: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 StringResources,且有一個名為的包裝函式類別 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. 不過,嘗試取得資源會擲回例外狀況 MissingManifestResourceExceptionHowever, the attempt to retrieve a resource throws a MissingManifestResourceException exception. 如需處理例外狀況的詳細資訊,請參閱本文稍後的 處理 system.resources.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.exe 之可執行檔的原始程式碼。It contains the source code for an executable named ShowTime.exe. 它也包含下列名為 Strings.txt,其中包含單一字串資源的文字檔 TimeHeaderIt 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 和 Culture-Specific 資源ResourceManager and Culture-Specific Resources

當地語系化的應用程式需要部署資源,如 封裝和部署資源一文所述。A localized app requires resources to be deployed, as discussed in the article Packaging and Deploying Resources. 如果已正確設定元件,則資源管理員會根據目前線程的屬性來決定要取出的資源 Thread.CurrentUICultureIf 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). 如果 CurrentUICulture 屬性設定為 fr-fr,則 ResourceManager 物件一律會抓取法文 (法國) 資源,即使使用者的作業系統語言不是法文也一樣。If 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 表示該文化特性的物件指派給靜態屬性,來設定應用程式域中所有線程的 UI 文化 CultureInfo.DefaultThreadCurrentUICulture 特性。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 文化特性,而且未定義目前應用程式域的預設文化特性,則 CultureInfo.CurrentUICulture 會由 Windows 函式隱含設定屬性 GetUserDefaultUILanguageIf 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 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 資源包含在名為 Greetings.txt 的文字檔中: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=Всем привет!

以下是適用于 c # 版本之 Visual Basic 版本或範例 .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 而非 vbc ,而不是 Example.cs Example.vbIf 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 和 Culture-Specific 資源See the previous section, ResourceManager and Culture-Specific Resources, for more information about how the current UI culture of a thread is defined. 如果 resource manager 找不到目前線程 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. 如果 resource manager 找不到任何當地語系化的資源,則會使用預設文化特性的資源。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.

注意

如果找不到類別的函式中指定的 .resources 檔案 ResourceManager ,則嘗試取得資源會擲回 MissingManifestResourceExceptionMissingSatelliteAssemblyException 例外狀況。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. 如需處理例外狀況的詳細資訊,請參閱本主題稍後的 處理 system.resources.missingmanifestresourceexception 和 System.resources.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-fr) 和俄文 (俄羅斯) (ru-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. 每個都有一個名為的單一字串資源 DateStartEach has a single string resource named DateStart.

文化特性Culture 檔案名稱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 СегодняСегодня

以下是此範例的原始程式碼 (針對 c # 版程式碼) 的 Visual Basic version 或 ShowDate 版本的 ShowDate。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 而非 vbc ,而不是 showdate.cs showdate.vbIf 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. 在方法呼叫中,您可以判斷如果 resource manager 找不到當地語系化的資源,或它是否只是切換回預設文化特性的資源,就會探查父文化特性。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.

處理 System.resources.missingmanifestresourceexception 和 System.resources.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 ),而不是當您具現化物件時,就會擲回例外狀況 ResourceManagerNote 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.dll,而且應該位於名為之後它所包含之資源的文化特性的目錄。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. NeutralResourcesLanguageAttribute 屬性新增至原始程式碼檔或專案資訊檔 (AssemblyInfo 適用于 c # 應用程式) 檔案的 Visual Basic 應用程式或 AssemblyInfo。Add 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.

  • 在函式 baseName 中的參數 ResourceManager(String, Assembly) 未指定 .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
    

如果您要明確變更應用程式的目前文化特性,您也應該記住,resource manager 會根據 CultureInfo.CurrentUICulture 屬性值(而非屬性)來抓取資源集 CultureInfo.CurrentCultureIf 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.

    針對 PublicKeyToken 屬性, null 如果您未使用強式名稱簽署元件,請指定關鍵字,如果您已經簽署元件,請指定公開金鑰 token。For 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.

    針對 Culture 屬性,指定關鍵字以指定 neutral 主要元件,並讓 ResourceManager 類別只探查節點中列出的文化特性 <culture>For 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 Create and use 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 Store 應用程式中支援類別,但不建議使用。Although the ResourceManager class is supported in Windows 8.x Store apps, we do not recommend its use. 只有當您開發可用於 Windows 8. x 商店應用程式的可移植類別庫專案時,才能使用這個類別。Use this class only when you develop Portable Class Library projects that can be used with Windows 8.x Store apps. 若要從 Windows 8. x Store 應用程式取出資源,請改用 ResourceLoader 類別。To retrieve resources from Windows 8.x Store apps, use the Windows.ApplicationModel.Resources.ResourceLoader class instead.

針對 Windows 8. x 儲存區應用程式, ResourceManager 類別會從封裝資源索引 (PRI) 檔取得資源。For 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 公用程式,從一或多個資源檔中,建立一個或多個資源檔,) 格式的 XML ( 資源。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 Store 應用程式具現化物件。You can instantiate a ResourceManager object for a 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 代表要抓取其資源的文化特性(culture)至方法的文化特性,來取得特定文化特性的資源 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)

初始化 ResourceManager 類別的新執行個體,這個執行個體使用指定的 ResourceSet 類別查閱所指組件中具有指定根名稱的檔案所包含的資源。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)

從指定的資源傳回 Unmanaged 記憶體資料流物件。Returns an unmanaged memory stream object from the specified resource.

GetStream(String, CultureInfo)

使用指定的文化特性,從指定的資源傳回 Unmanged 記憶體資料流物件。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.

另請參閱