System.Resources.ResourceManager 建構函式

本文提供此 API 參考文件的補充備註。

ResourceManager(Type) 建構函式

本節與建 ResourceManager(Type) 構函式多載有關。

傳統型應用程式

在傳統型應用程式中,資源管理員會使用 resourceSource 參數來載入特定資源檔,如下所示:

  • NeutralResourcesLanguageAttribute如果屬性不是用來指出預設文化特性的資源位於附屬元件中,資源管理員會假設預設文化特性的資源檔位於與 參數所resourceSource指定的類型相同的元件中。
  • 資源管理員假設預設資源檔與 參數所 resourceSource 指定的類型具有相同基底名稱。
  • 資源管理員會使用預設 ResourceSet 類別來操作資源檔。

例如,假設類型為 MyCompany.MyProduct.MyType,資源管理員會在定義 MyType的元件中尋找名為 MyCompany.MyProduct.MyType.resources 的 .resources 檔案。

在 Visual Studio 中,資源設計工具會自動產生程式代碼,其名稱與預設文化特性之 .resources 檔案的基底名稱相同,以定義 internal (在 C# 中) 或 Friend [Visual Basic] 類別。 這可讓您具現化 ResourceManager 物件,並結合一組特定的資源,方法是取得名稱對應至資源名稱的類型對象,因為只要類別對編譯程式可見,資源也必須一樣。 例如,如果 .resources 檔案名為 Resource1,下列語句會具現化 ResourceManager 物件來管理名為 Resource1 的 .resources 檔案:

ResourceManager rm = new ResourceManager(typeof(Resource1));

如果您未使用 Visual Studio,您可以建立沒有成員的類別,其命名空間和名稱與預設 .resources 檔案的成員相同。 這個範例將提供說明。

Windows 8.x 應用程式

重要

雖然 Windows 8.x 應用程式中支援 類別 ResourceManager ,但我們不建議使用類別。 只有在您開發可與 Windows 8.x 應用程式搭配使用的可攜式類別庫專案時,才使用此類別。 若要從 Windows 8.x 應用程式擷取資源,請改用 Windows.ApplicationModel.Resources.ResourceLoader 類別。

在 Windows 8.x 應用程式中, ResourceManager 使用 resourceSource 參數來推斷元件、基底名稱和命名空間,其中資源專案可以位於應用程式的套件資源索引 (PRI) 檔案中。 例如,假設在 中定義的類型MyCompany.MyProduct.MyType,資源管理員會尋找名為 MyAssembly 的資源集標識碼,並尋找該資源集內的範圍MyCompany.MyProduct.MyTypeMyAssembly 資源管理員會在此範圍內搜尋預設內容下的資源專案(目前文化特性、目前的高對比度設定等等)。

範例

下列範例會使用 建 ResourceManager(Type) 構函式來具現化 ResourceManager 物件。 它由英文(en)、法文(法國)(fr-FR)和俄羅斯(俄羅斯)(ru-RU)文化.txt檔案所編譯的資源組成。 此範例會將目前的文化和目前的UI文化特性變更為英文(美國)、法文(法國)、俄文(俄羅斯)和瑞典文(瑞典)。 然後,它會呼叫 GetString(String) 方法來擷取本地化的字串,其會顯示視一天時間而定的問候語。

此範例需要三個以文字為基礎的資源檔,如下表所列。 每個檔案都包含名為 MorningAfternoon和 的 Evening字串資源。

文化特性 File name 資源名稱 資源值
zh-TW GreetingResources.txt Morning 早安
zh-TW GreetingResources.txt Afternoon 午安
zh-TW GreetingResources.txt Evening 晚安
fr-FR GreetingResources.fr-FR.txt Morning Bonjour
fr-FR GreetingResources.fr-FR.txt Afternoon Bonjour
fr-FR GreetingResources.fr-FR.txt Evening Bonsoir
ru-RU GreetingResources.ru-RU.txt Morning Доброе утро
ru-RU GreetingResources.ru-RU.txt Afternoon Добрый день
ru-RU GreetingResources.ru-RU.txt Evening Добрый вечер

您可以使用下列批處理文件來編譯 Visual Basic 範例,並建立名為 Greet.exe 的可執行檔。 若要使用 C# 編譯,請將編譯程式名稱從 vbc 變更為 csc ,並將擴展名從 .vb 變更為 .cs

resgen GreetingResources.txt
vbc Greet.vb /resource: GreetingResources.resources

md fr-FR
resgen GreetingResources.fr-FR.txt
al /out:fr-FR\Greet.resources.dll /culture:fr-FR /embed: GreetingResources.fr-FR.resources

md ru-RU
resgen GreetingResources.ru-RU.txt
al /out:ru-RU\Greet.resources.dll /culture:ru-RU /embed: GreetingResources.ru-RU.resources

以下是範例的原始碼(適用於 Visual Basic 版本的ShowDate.vb,或 C# 版本的程式代碼ShowDate.cs)。

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

[assembly: NeutralResourcesLanguage("en")]

public class Example2
{
    public static void Main()
    {
        string[] cultureNames = [ "en-US", "fr-FR", "ru-RU", "sv-SE" ];
        DateTime noon = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
                                     DateTime.Now.Day, 12, 0, 0);
        DateTime evening = new DateTime(DateTime.Now.Year, DateTime.Now.Month,
                                        DateTime.Now.Day, 18, 0, 0);

        ResourceManager rm = new ResourceManager(typeof(GreetingResources));

        foreach (var cultureName in cultureNames)
        {
            Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cultureName);
            Console.WriteLine("The current UI culture is {0}",
                              CultureInfo.CurrentUICulture.Name);
            if (DateTime.Now < noon)
                Console.WriteLine("{0}!", rm.GetString("Morning"));
            else if (DateTime.Now < evening)
                Console.WriteLine("{0}!", rm.GetString("Afternoon"));
            else
                Console.WriteLine("{0}!", rm.GetString("Evening"));
            Console.WriteLine();
        }
    }

    internal class GreetingResources
    {
    }
}
// The example displays output like the following:
//       The current UI culture is en-US
//       Good afternoon!
//
//       The current UI culture is fr-FR
//       Bonjour!
//
//       The current UI culture is ru-RU
//       Добрый день!
//
//       The current UI culture is sv-SE
//       Good afternoon!
Imports System.Resources
Imports System.Globalization
Imports System.Threading

<Assembly:NeutralResourcesLanguage("en")>

Module Example
   Public Sub Main()
      Dim cultureNames() As String = {"en-US", "fr-FR", "ru-RU", "sv-SE" }
      Dim noon As New Date(Date.Now.Year, Date.Now.Month, 
                           Date.Now.Day, 12,0,0)
      Dim evening As New Date(Date.Now.Year, Date.Now.Month,
                              Date.Now.Day, 18, 0, 0)                          
      
      Dim rm As New ResourceManager(GetType(GreetingResources))
      
      For Each cultureName In cultureNames
         Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(cultureName)
         Console.WriteLine("The current UI culture is {0}", 
                           CultureInfo.CurrentUICulture.Name)
         If Date.Now < noon Then
            Console.WriteLine("{0}!", rm.GetString("Morning"))
         ElseIf Date.Now < evening Then
            Console.WriteLine("{0}!", rm.GetString("Afternoon"))
         Else
            Console.WriteLine("{0}!", rm.GetString("Evening"))
         End If 
         Console.WriteLine()
      Next
   End Sub
End Module

Friend Class GreetingResources
End Class
' The example displays output like the following:
'       The current UI culture is en-US
'       Good afternoon!
'       
'       The current UI culture is fr-FR
'       Bonjour!
'       
'       The current UI culture is ru-RU
'       Добрый день!
'       
'       The current UI culture is sv-SE
'       Good afternoon!

除了定義名為 Example的應用程式類別之外,原始程式碼也會定義名稱為的內部類別,其名稱 GreetingResources與資源檔的基底名稱相同。 這可藉由呼叫 ResourceManager(Type) 建構函式,成功具現化 ResourceManager 物件。

請注意,輸出會顯示適當的當地語系化字串,但目前的UI文化特性是瑞典文(瑞典),在此情況下,它會使用英文語言資源。 由於瑞典文語言資源無法使用,因此應用程式會改用屬性所 NeutralResourcesLanguageAttribute 定義的預設文化特性資源。

ResourceManager(String, Assembly) 建構函式

本節與建 ResourceManager(String, Assembly) 構函式多載有關。

傳統型應用程式

在傳統型應用程式中,個別文化特性特定的資源檔應該包含在附屬元件中,而預設文化特性的資源文件應該包含在主要元件中。 假設附屬元件包含該元件指令清單中所指定之單一文化特性的資源,並視需要載入。

注意

若要直接從 .resources 檔案擷取資源,而不是從元件中擷取資源,您必須改為呼叫 CreateFileBasedResourceManager 方法來具現化 ResourceManager 物件。

如果在 中找不到 所baseName識別的資源檔,則 方法會具現化 ResourceManager 物件,但嘗試擷取特定資源會擲回例外狀況,通常是 MissingManifestResourceExceptionassembly 如需診斷例外狀況原因的相關信息,請參閱類別主題的 ResourceManager <處理MissingManifestResourceException 例外狀況>一節。

Windows 8.x 應用程式

重要

雖然 Windows 8.x 應用程式中支援 類別 ResourceManager ,但我們不建議使用類別。 只有在您開發可與 Windows 8.x 應用程式搭配使用的可攜式類別庫專案時,才使用此類別。 若要從 Windows 8.x 應用程式擷取資源,請改用 Windows.ApplicationModel.Resources.ResourceLoader 類別。

在 Windows 8.x 應用程式中,資源管理員會使用 參數的 assembly 簡單名稱,在應用程式的套件資源索引 (PRI) 檔案中查閱相符的資源集。 baseName參數是用來在資源集合內查詢資源專案。 例如,PortableLibrary1.Resource1.de-DE.resources 的根名稱是 PortableLibrary1.Resource1。

範例

下列範例使用簡單的非本地化 「Hello World」 應用程式來說明建 ResourceManager(String, Assembly) 構函式。 名為 ExampleResources.txt 的文字檔案的內容為 Greeting=Hello。 編譯應用程式時,資源會內嵌在主要應用程式元件中。

文字檔可以使用命令提示字元中的 資源檔案產生器 (ResGen.exe) 轉換成二進位資源檔,如下所示:

resgen ExampleResources.txt

下列範例提供可具現化 ResourceManager 物件的可執行程式碼、提示使用者輸入名稱,並顯示問候語。

using System;
using System.Reflection;
using System.Resources;

public class Example1
{
    public static void Main()
    {
        // Retrieve the resource.
        ResourceManager rm = new ResourceManager("ExampleResources",
                                 typeof(Example).Assembly);
        string greeting = rm.GetString("Greeting");

        Console.Write("Enter your name: ");
        string name = Console.ReadLine();
        Console.WriteLine("{0} {1}!", greeting, name);
    }
}
// The example produces output similar to the following:
//       Enter your name: John
//       Hello John!
Imports System.Globalization
Imports System.Reflection
Imports System.Resources

Module Example1
    Public Sub Main()
        ' Retrieve the resource.
        Dim rm As New ResourceManager("ExampleResources",
                                      GetType(Example).Assembly)
        Dim greeting As String = rm.GetString("Greeting")

        Console.Write("Enter your name: ")
        Dim name As String = Console.ReadLine()
        Console.WriteLine("{0} {1}!", greeting, name)
    End Sub
End Module
' The example produces output similar to the following:
'       Enter your name: John
'       Hello John!

您可以使用 C# 中的下列命令來編譯它:

csc Example.cs /resource:ExampleResources.resources

此範例會擷取包含資源檔的元件參考,方法是將定義於該元件中的型別傳遞至 typeof 函式 (在 C# 中)或函 GetType 式 (在 Visual Basic 中),並擷取其 Type.Assembly 屬性的值。