C# 检查对象是否为空
假设我有一个名为Customer的类(由实体框架自动生成) 现在在我的ViewModel中:C# 检查对象是否为空,c#,wpf,silverlight,mvvm,C#,Wpf,Silverlight,Mvvm,假设我有一个名为Customer的类(由实体框架自动生成) 现在在我的ViewModel中: public Class myViewModel : INotifyPropertyChanged { public Customer CurrentCustomer { get { return MainViewModel.cCustomer; } set {
public Class myViewModel : INotifyPropertyChanged
{
public Customer CurrentCustomer
{
get
{
return MainViewModel.cCustomer;
}
set
{
myViewModel.cCustomer = value;
OnPropertyChanged("CurrentCustomer");
}
}
....
....
....
}
这是我的主视图模型
public Class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
cCustomer = new Customer();
}
public static Customer cCustomer { get; set; }
public void SaveChanges()
{
//Here I want to check if all the fields of cCustomer are empty
//And depending on that I want to save the cCustomer.
}
....
....
....
}
我试图通过将cCustomer的所有字段比较为null来检查它们,但是在那里我得到一个错误,指出对象引用没有设置为对象的实例
简言之,我想在保存客户时检查cCustomer是否为null。您的
cCustomer
可能是null
(属性集上没有验证)-很容易检查:
if (cCustomer == null)
{
// No Customer record, so don't even think about checking properties on it.
// feel free to throw an exception if it's not valid to save without one...
}
不要在那里那样做。。。这应该是数据模型的一部分。如果您的要求是不应有
null
值,则在类属性级别执行此操作:
public string Text
{
get { return text; }
set { if (value != null) { text = value; NotifyPropertyChanged("Text"); } }
}
您的
MainViewModel
类将cCustomer
属性声明为静态,但您正在类构造函数中设置该属性:
public Class MainViewModel : INotifyPropertyChanged
{
public MainViewModel()
{
cCustomer = new Customer();
}
public static Customer cCustomer { get; set; }
因此,当您尝试静态访问这些行中的cCustomer
属性时,它可能不会被填充:
get
{
// Unless you've created an instance of a MainViewModel already,
// this property will be null
return MainViewModel.cCustomer;
}
set
{
myViewModel.cCustomer = value;
OnPropertyChanged("CurrentCustomer");
}
是否确实希望
cCustomer
属性是静态的?此外,在实例构造函数内的类上设置静态属性可能是一种不好的做法,应该避免。如果(cCustomer!=null)
不起作用?连接调试器,看看什么是null?cCustomer是否实例化或初始化过?@Tim(!(cCustomer==null))太麻烦,无法读取。如果cCustomer
为null,则可能需要(cCustomer!=null),因为您将无法检查字段,因此需要先查看包含的对象(cCustomer
)是否为null。如果不是,那么您可以检查各个属性。我的要求不是不应该有空值。我想深入地向你解释我的问题。我的项目有15页。在主窗口上,我有一个框架和一个菜单,所以用户可以从一个页面导航到另一个页面,他们可能会在某些页面中填充值,甚至可能不会打开某些页面。当用户完成后,他/她必须单击保存按钮,这是保存更改的唯一方法,该按钮位于我的主窗口上。这并不是那么容易。正如我在问题中提到的,我在MainViewModel的构造函数中调用了cCustomer=new Customer()。因此,cCustomer永远不会为null,但也可以为null,例如:var model=newmainviewmodel();model.cCustomer=null代码>。当然,您的调试器是一个很棒的工具,用于检查空值,并在空值变为空时设置断点。我将该成员设置为静态,因为我想在myViewModel
中访问myMainviewmodel
的当前实例。如果有任何方法可以访问mainViewModel的当前实例,请提出建议。
get
{
// Unless you've created an instance of a MainViewModel already,
// this property will be null
return MainViewModel.cCustomer;
}
set
{
myViewModel.cCustomer = value;
OnPropertyChanged("CurrentCustomer");
}