1

我想做一个多语言应用程序。

我这样做(从 UI 绑定):

private CultureInfo _culture;
public CultureInfo Culture
{
    get { return _culture; }
    set
    {
        if (_culture != value)
        {
            RaisePropertyChanging(() => Culture);
            _culture = value;
            RaisePropertyChanged(() => Culture);

            if (CultureManager.UICulture.Name != _culture.Name)
            {
                CultureManager.UICulture = _culture;  // line A
            }
        }
    }
}

但在 A 行,出现异常:

用户代码未处理 NullReferenceException

会是什么?

4

1 回答 1

1

在您指示的行上不太可能引发异常。更有可能的是,它被抛出if,因为_cultureis null

您要么需要null通过添加保护子句来禁止将文化设置为:

    private CultureInfo _culture;
    public CultureInfo Culture
    {
        get { return _culture; }
        set
        {
            if(value == null)
                throw new ArgumentNullException("value");
            if (_culture != value)
            {
                RaisePropertyChanging(() => Culture);
                _culture = value;
                RaisePropertyChanged(() => Culture);

                if (CultureManager.UICulture.Name != _culture.Name)
                {
                CultureManager.UICulture = _culture;  // line A
                }
             }
        }
    }

或者,如果设置了文化,您只能更改 UI 文化:

if (_culture != null && CultureManager.UICulture.Name != _culture.Name)
{
    CultureManager.UICulture = _culture;  // line A
}
于 2013-09-09T07:29:50.403 回答