我们想枚举 .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