

一行的开头是键名,空格后是本地化字符串。
public class YamlStringLocalizer : IHtmlLocalizer
{
private readonly Dictionary languageDictionary = new Dictionary();
public LocalizedString GetString(string name) { throw new NotImplementedException(); }
public LocalizedString GetString(string name, params object[] arguments) { throw new NotImplementedException(); }
public IEnumerable GetAllStrings(bool includeParentCultures) { throw new NotImplementedException(); }
public IHtmlLocalizer WithCulture(CultureInfo culture) { throw new NotImplementedException(); }
public LocalizedHtmlString this[string name]
{
get
{
var ci = CultureInfo.CurrentCulture;
var languageName = ci.IsNeutralCulture ? ci.EnglishName : ci.Parent.EnglishName;
var path = @"D:\Documents\Paradox Interactive\Stellaris\mod\cn\localisation\l.${languageName}.yml";
if (languageDictionary.TryGetValue(languageName, out var content) == false)
{
if (File.Exists(path) == false)
return new LocalizedHtmlString(name, name, true, path);
content = File.ReadAllText(path);
languageDictionary.Add(languageName, content);
}
var regex = new Regex(@"^\s*" + name + @":\s+""(.*?)""\s*$", RegexOptions.Multiline);
var match = regex.Match(content);
if (match.Success)
{
var value = match.Groups[1].Value;
return new LocalizedHtmlString(name, value);
}
else
{
return new LocalizedHtmlString(name, name, true, path);
}
}
}
public LocalizedHtmlString this[string name, params object[] arguments] => throw new NotImplementedException();
}代码很简单,读取l.yml的所有文字,保存在缓存中,然后用正则表达式匹配键。
在视图里,我们需要改用YamlStringLocalizer。
@inject Microsoft.AspNetCore.Mvc.Localization.IViewLocalizer Lo @inject YamlStringLocalizer YLo
但是YamlStringLocalizer还没有向依赖注入注册,所以还要把Startup.ConfigureServices()改成
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton();
services.AddMvc()
.AddViewLocalization(Microsoft.AspNetCore.Mvc.Razor.LanguageViewLocationExpanderFormat.Suffix,
opt => { opt.ResourcesPath = "Resources"; })
......
}总结
