Lan.cs 1.37 KB
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;

namespace HHECS.Web
{
    public class Lan
    {
        private static readonly Type ResourceType = typeof(HHECS.Web.Resources.Shared._Layout);

        // 使用Lazy初始化确保线程安全
        private static readonly Lazy<Dictionary<string, PropertyInfo>> PropertyCache =
            new Lazy<Dictionary<string, PropertyInfo>>(() =>
            {
                var properties = ResourceType.GetProperties(
                    BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);

                return properties.ToDictionary(p => p.Name, p => p);
            });

        public static string Get(string key)
        {
            var cache = PropertyCache.Value;

            if (cache.TryGetValue(key, out var property))
            {
                return property.GetValue(null) as string ?? $"[{key}]";
            }

            return $"[{key}]";
        }

        // 添加一个方法支持默认值
        public static string Get(string key, string defaultValue)
        {
            var cache = PropertyCache.Value;

            if (cache.TryGetValue(key, out var property))
            {
                return property.GetValue(null) as string ?? defaultValue;
            }

            return defaultValue;
        }
    }
}