gpt4 book ai didi

.net-core - .NET 5.0 Blazor IStringLocalizer 和区分大小写

转载 作者:行者123 更新时间:2023-12-05 04:53:03 30 4
gpt4 key购买 nike

我正在使用 IStringLoclizer使用 resx 的方法包含键值对的文件,用于本地化我的应用程序,如 the documentation 中所述.

我刚刚发现:

一方面.resx文件大小写不敏感(存储 key FirstnameFirstName 将引发 key 已存在的错误)。

另一方面,当我想检索键时,它区分大小写(如果键 Firstname 存在并且我想获取 FirstName 的值,则值为未被 IStringLoclizer 检索 - 从键值对的角度来看这是有意义的!)。

有没有办法覆盖 IStringLocalizer setter/getter ,以实现一些逻辑(例如,将所有键更改为小写,并按小写搜索任何键)?有效解决方案的关键是避免更改 .resx 中的所有键。文件和我称之为 IStringLocalizer 的任何地方.

编辑我发现了 ResourceManager.IgnoreCase here , 但我不清楚如何访问资源管理器 - 可能必须在 Startup.cs 中完成不知何故?

最佳答案

这可以通过覆盖 ResourceManagerStringLocalizerFactory 来实现。

public class CaseInsensitiveResourceManagerStringLocalizerFactory : ResourceManagerStringLocalizerFactory
{
public CaseInsensitiveResourceManagerStringLocalizerFactory(IOptions<LocalizationOptions> localizationOptions, ILoggerFactory loggerFactory) : base(localizationOptions, loggerFactory)
{
}

//unfortunately we need to use reflection to the the ResourceManager as the field is private
private readonly FieldInfo _field = typeof(ResourceManagerStringLocalizer).GetField("_resourceManager", BindingFlags.NonPublic | BindingFlags.Instance);

//override this method to access the resource manager at the time it is created
protected override ResourceManagerStringLocalizer CreateResourceManagerStringLocalizer(Assembly assembly, string baseName)
{
//call the base method to get the localizer, I would like to override this implementation but the fields used in the construction are private
var localizer = base.CreateResourceManagerStringLocalizer(assembly, baseName);
if (_field == null) return localizer;
//set the resource manager to ignore case
if (_field.GetValue(localizer) is ResourceManager resourceManager) resourceManager.IgnoreCase = true;
return localizer;
}
}

您需要在添加本地化之前注册工厂。

public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IStringLocalizerFactory, CaseInsensitiveResourceManagerStringLocalizerFactory>();
services.AddLocalization(options => { options.ResourcesPath = "Resources"; });

//other service configurations....
}

我希望将来这些类更具可扩展性。 ResourceManagerStringLocalizerFactoryResourceManagerStringLocalizer 中的私有(private)字段需要反射。

关于.net-core - .NET 5.0 Blazor IStringLocalizer 和区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66194098/

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