我们想枚举.NET(resx文件)中资源文件中的所有字符串。我们希望这生成一个包含所有这些键值对的javascript对象。我们现在为具有这样的代码的卫星程序集执行此操作(这是VB.NET,但任何示例代码都可以):

Dim rm As ResourceManager
rm = New ResourceManager([resource name], [your assembly])
Dim Rs As ResourceSet
Rs = rm.GetResourceSet(Thread.CurrentThread.CurrentCulture, True, True)
For Each Kvp As DictionaryEntry In Rs
    [Write out Kvp.Key and Kvp.Value]
Next

然而,遗憾的是,我们还没有找到为.resx文件执行此操作的方法。我们如何枚举resx文件中的所有本地化字符串?

更新:

遵循Dennis Myren的评论和这里,我构建了一个ResXResourceManager。现在,我可以像使用嵌入式资源一样使用.resx文件。这是代码。请注意,Microsoft将所需的构造函数设为私有,因此我使用反射来访问它。使用它时需要完全信任。

Imports System.Globalization
Imports System.Reflection
Imports System.Resources
Imports System.Windows.Forms

Public Class ResXResourceManager
    Inherits ResourceManager

    Public Sub New(ByVal BaseName As String, ByVal ResourceDir As String)
        Me.New(BaseName, ResourceDir, GetType(ResXResourceSet))
    End Sub

    Protected Sub New(ByVal BaseName As String, ByVal ResourceDir As String, ByVal UsingResourceSet As Type)
        Dim BaseType As Type = Me.GetType().BaseType
        Dim Flags As BindingFlags = BindingFlags.NonPublic Or BindingFlags.Instance
        Dim Constructor As ConstructorInfo = BaseType.GetConstructor(Flags, Nothing, New Type() { GetType(String), GetType(String), GetType(Type) }, Nothing)
        Constructor.Invoke(Me, Flags, Nothing, New Object() { BaseName, ResourceDir, UsingResourceSet }, Nothing)
    End Sub

    Protected Overrides Function GetResourceFileName(ByVal culture As CultureInfo) As String
        Dim FileName As String
        FileName = MyBase.GetResourceFileName(culture)
        If FileName IsNot Nothing AndAlso FileName.Length > 10 Then
            Return FileName.Substring(0, FileName.Length - 10) & ".resx"
        End If
        Return Nothing
    End Function
End Class
有帮助吗?

解决方案

使用 System.Resources.ResXResourceReader (它位于System.Windows.Forms.dll)

其他提示

http:// tonesdotnetblog.wordpress.com/2010/02/14/string-enumerations-and-resource-files-in-c/ 有一个替代解决方案,涉及将属性放在枚举上,以便从资源文件中读取字符串。这使用了另一种自定义工具。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top