58 lines
2.4 KiB
C#
58 lines
2.4 KiB
C#
using System.Globalization;
|
|
using System.Resources;
|
|
using XP.Common.Localization.Interfaces;
|
|
using XP.Common.Resources;
|
|
|
|
namespace XP.Common.Localization
|
|
{
|
|
/// <summary>
|
|
/// 静态本地化帮助类 | Static localization helper
|
|
/// 用法:Loc.Get("ResourceKey") 或 Loc.Get("ResourceKey", param1, param2)
|
|
/// Usage: Loc.Get("ResourceKey") or Loc.Get("ResourceKey", param1, param2)
|
|
/// </summary>
|
|
public static class LocalizationHelper
|
|
{
|
|
private static ILocalizationService? _localizationService;
|
|
|
|
/// <summary>
|
|
/// 初始化本地化帮助类(由 CommonModule 或 App 启动时调用)
|
|
/// Initialize the localization helper (called by CommonModule or App at startup)
|
|
/// </summary>
|
|
/// <param name="localizationService">本地化服务实例 | Localization service instance</param>
|
|
public static void Initialize(ILocalizationService localizationService)
|
|
{
|
|
_localizationService = localizationService;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 获取本地化字符串(使用当前 UI 语言)| Get localized string (using current UI culture)
|
|
/// </summary>
|
|
/// <param name="key">资源键 | Resource key</param>
|
|
/// <returns>本地化字符串,找不到时返回键本身 | Localized string, returns key itself if not found</returns>
|
|
public static string Get(string key)
|
|
{
|
|
if (string.IsNullOrEmpty(key))
|
|
return string.Empty;
|
|
|
|
if (_localizationService != null)
|
|
return _localizationService.GetString(key);
|
|
|
|
// 兼容回退:未初始化时仍使用原始 ResourceManager
|
|
// Fallback: use original ResourceManager when not initialized
|
|
return Resources.Resources.ResourceManager.GetString(key, CultureInfo.CurrentUICulture) ?? key;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 获取本地化字符串并格式化 | Get localized string with formatting
|
|
/// </summary>
|
|
/// <param name="key">资源键 | Resource key</param>
|
|
/// <param name="args">格式化参数 | Format arguments</param>
|
|
/// <returns>格式化后的本地化字符串 | Formatted localized string</returns>
|
|
public static string Get(string key, params object[] args)
|
|
{
|
|
var template = Get(key);
|
|
return args.Length > 0 ? string.Format(template, args) : template;
|
|
}
|
|
}
|
|
}
|