gpt4 book ai didi

.NET:通过反射获取资源

转载 作者:行者123 更新时间:2023-12-04 20:15:10 25 4
gpt4 key购买 nike

如何从当前程序集中动态获取所有资源?我尝试了两种方法,GetManifestResourceNames 和 GetResourceSet,但均未成功。我对 VB.net 或 C# 中的解决方案很满意。

第一种方法

第一个方法只返回长度为 1 的数组,值为“MyNameSpace.Resources.resource”。问题是此文件中有超过 1 个资源。

Dim ca As Assembly = Assembly.GetExecutingAssembly
Dim rn() As String = CurrentAssembly.GetManifestResourceNames()

第二种方法

Dim ca As Assembly = Assembly.GetExecutingAssembly
Dim crm As New ResourceManager("", ca)
''//Dim CurrentResourceManager As New ResourceManager(_
"MyNamespace.Resources.resources", CurrentAssembly)
''//Dim CurrentResourceManager As New ResourceManager( _
"My.Resources", CurrentAssembly)
Dim rs As ResourceSet = CurrentResourceManager.GetResourceSet(CultureInfo.CurrentCulture, True, True)
Dim rs As ResourceSet = crm.GetResourceSet( _
CultureInfo.CurrentCulture, True, True)

MissingManifestResourceException 未处理

Could not find any resources appropriate for the specified culture or the neutral culture. Make sure ".resources" was correctly embedded or linked into assembly "MyProgram" at compile time, or that all the satellite assemblies required are loadable and fully signed.loadable and fully signed.

解决方案(根据 Hans Passant)

从 Resources.Designer.vb 复制命名空间

<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)>  _
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
Get
If Object.ReferenceEquals(resourceMan, Nothing) Then
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("MyNamespace.Resources", GetType(Resources).Assembly)
resourceMan = temp
End If
Return resourceMan
End Get
End Property

并将其放在代码中

Dim CurrentResourceManager As New ResourceManager( _
"MyNamespace.Resources", CurrentAssembly)
Dim rs As ResourceSet = CurrentResourceManager.GetResourceSet( _
CultureInfo.CurrentCulture, True, True)

最佳答案

是的,MyNameSpace.Resources.resource 中有不止 1 个资源。这是您必须传递给 ResourceManager 的名称,空字符串是行不通的。

要查看您必须编写的代码类型,请启动 Windows 窗体应用程序并将一些资源添加到“项目 + 属性”、“资源”选项卡。在解决方案资源管理器中,单击“显示所有文件”图标。打开我的项目节点,打开 Resources.resx 节点并双击 Resources.Designer.vb 文件。请注意 ResourceManager 属性的代码。

关于.NET:通过反射获取资源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3643924/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com