CultureInfo的包装

时间:2016-09-05 09:24:58

标签: c# cultureinfo

我想创建一个包装类来替换CultureInfo基类。例如;在我的代码中我有

var cultureInfo = new CultureInfo (stringVariableForCultureName);   

我想替换另一行:

var cultureInfo = new CultureInfoWrapper (stringVariableForCultureName);

原因是我无法控制传递给初始化CultureInfo的值,我想避免错误导致默认的CultureInfo

所以我的CultureInfoWrapper构造函数应该是这样的:

public CultureInfoWrapper(string cultureName)
{
    try
    {
        return new CultureInfo(cultureName);
    }
    catch (Exception exception)
    {   
        return new CultureInfo(DefaultCultureName);
    }
}

你能帮我定一下包装类吗?

1 个答案:

答案 0 :(得分:5)

您可以使用此实现,请注意我已处理CultureNotFoundException

public class CultureInfoWrapper
{
    private readonly CultureInfo _cultureInfo;

    public CultureInfo Value
    {
        get { return _cultureInfo; }
    }

    public CultureInfoWrapper(string cultureName, string fallbackCultureName = "en-US")
    {
        try
        {
            _cultureInfo = new CultureInfo(cultureName);
        }
        catch (CultureNotFoundException)
        {
            _cultureInfo = new CultureInfo(fallbackCultureName);
        }
    }
}

另一种方法是加载所有培养物一次,然后就可以使用这个优化版本:

public class CultureInfoFinder
{
    private static readonly CultureInfo DefaultCulture = new CultureInfo("en-US");

    private static Dictionary<string, CultureInfo> _allSpecificCultures;

    static CultureInfoFinder()
    {
        _allSpecificCultures = CultureInfo.GetCultures(CultureTypes.SpecificCultures)
            .ToDictionary(c => c.ToString(), c => c, StringComparer.InvariantCultureIgnoreCase);
    }

    public static CultureInfo Get(string cultureName)
    {
        CultureInfo c;
        bool knownCulture = _allSpecificCultures.TryGetValue(cultureName, out c);
        return knownCulture ? c : DefaultCulture;
    }
}

例如:

CultureInfo deDE = CultureInfoFinder.Get("de-DE");