我想制作一个多语种应用程序。
我这样做(从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未被用户代码
处理
它有什么用?
答案 0 :(得分:1)
您指示的行不太可能抛出异常。更有可能的是,它被if
抛出,因为_culture
是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
}