簡體   English   中英

C#:如何從某種文化中獲取資源字符串

[英]C#: How to get a resource string from a certain culture

我有一個資源匯編,其中包含各種語言的翻譯文本。 項目看起來像這樣:

  • FooBar.resx
  • FooBar.nb-NO.resx
  • FooBar.sv-SE.resx
  • ...

我可以使用如下靜態屬性獲取文本:

var value = FooBar.Hello;

或者使用這樣的反射:

var value = resourceAssembly
      .GetType("Namespace.FooBar")
      .GetProperty("Hello")
      .GetValue(null, null) as string;

兩種方式都會使我獲得屬於當前線程的當前UI文化的值。 很好,完全是我通常想要的。

但是,如果我明確想要例如瑞典語的值而無需更改UI文化,是否可以做些什么?

您可以手動更改Visual Studio生成的FooBar類的Culture屬性。 或者,如果您直接使用ResourceManager類 ,則可以使用GetString的重載,該重載將所需的區域性作為參數。

請嘗試以下代碼。 至少對我來說效果很好:

FooBar.ResourceManager.GetString("Hello", CultureInfo.GetCultureInfo("sv-SE"))

這是我用來按區域性名稱獲取資源文件的一些代碼-它是vb.net,但是您明白了。

Dim reader As New System.Resources.ResXResourceReader(String.Format(Server.MapPath("/App_GlobalResources/{0}.{1}.resx"), resourceFileName, culture))

如果您想將其作為字典返回:

If reader IsNot Nothing Then
    Dim d As New Dictionary(Of String, String)
    Dim enumerator As System.Collections.IDictionaryEnumerator = reader.GetEnumerator()
    While enumerator.MoveNext
        d.Add(enumerator.Key, enumerator.Value)
    End While
    Return d
End If

您可以在資源訪問類中手動更改區域性。 但這是不建議的,因為它會導致許多其他國際化問題。

例如,您將必須:

  • 處理所有帶有數字超載的數字格式
  • 確保您使用的其他庫具有與您類似的機制
  • 在上述情況無法實現的情況下(例如BCL),為可能是特定於文化的所有內容創建包裝(這是很多東西)。

因此,如有可能,請更改當前線程的當前UI文化。

使用GetValue的第二次重載:

 .GetValue(null, BindingFlags.GetProperty, null, null, CultureInfo.GetCultureInfo("sv-SE"))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM