.NET Maui如何判断字符串是否来自指定文化的资源文件?
检测.NET Maui本地化资源是否来自指定文化
要判断GetString返回的字符串是否来自指定文化的资源文件,核心是绕过ResourceManager的自动回退机制,直接检查目标文化的资源集中是否存在对应的ResourceID。
解决方案代码
可以扩展你的现有方法,添加文化检测逻辑:
public static (string? Text, bool IsFromSpecifiedCulture) TextWithCultureCheck(string? resourceFile, string? resourceId, CultureInfo targetCulture) { string? text = null; bool isFromTargetCulture = false; try { if (!string.IsNullOrEmpty(resourceFile) && !string.IsNullOrEmpty(resourceId)) { var resourceManager = GetResourceManager(resourceFile); if (resourceManager != null) { // 直接检查指定文化的资源集,不启用回退机制 using var targetResourceSet = resourceManager.GetResourceSet(targetCulture, createIfNotExists: false, tryParents: false); // 判断指定文化中是否存在该资源 isFromTargetCulture = targetResourceSet != null && targetResourceSet.GetString(resourceId, ignoreCase: false) != null; // 正常获取资源(包含回退逻辑) text = resourceManager.GetString(resourceId, targetCulture); if (text == string.Empty) text = null; } } } catch { text = null; isFromTargetCulture = false; } return (text, isFromTargetCulture); } // 保留你原有的GetResourceManager方法 private static ResourceManager? GetResourceManager(string resourceFile) { // 你的原有实现逻辑 }
关键逻辑说明
GetResourceSet(targetCulture, false, false):- 第二个参数
createIfNotExists设为false,不会自动创建不存在的资源集; - 第三个参数
tryParents设为false,禁止回退到父文化或中性文化,仅检查指定的目标文化资源文件。
- 第二个参数
- 通过判断目标资源集是否存在且能获取到对应字符串,确定返回的文本是否来自指定文化:
- 如果
isFromTargetCulture为true,说明文本来自目标文化的资源文件; - 如果为
false,说明文本是通过回退机制从其他文化(比如英语)获取的。
- 如果
使用示例
var culture = new CultureInfo("es-mx"); var result = TextWithCultureCheck("YourResourceFileName", "YourResourceID", culture); if (result.Text != null) { if (result.IsFromSpecifiedCulture) { // 文本来自es-mx资源文件 } else { // 文本是回退到其他文化的结果(比如英语) } }
内容的提问来源于stack exchange,提问作者Brian
相关产品推荐
相关产品推荐

