【问题标题】:check if object is null [closed]检查对象是否为空[关闭]
【发布时间】:2014-01-01 12:33:24
【问题描述】:

假设我有一个名为 Customer 的类(由实体框架自动生成)

CustomerID // Primary Key & Auto-increment
Name
Gender
City

现在在我的 ViewModel 中:

public Class myViewModel : INotifyPropertyChanged
{
    public Customer CurrentCustomer
    {
        get
        {
            return MainViewModel.cCustomer;
        }
        set
        {
            myViewModel.cCustomer = value;
            OnPropertyChanged("CurrentCustomer");
        }
    }

    ....
    ....
    ....

}

这是我的 MainViewModel

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 是否为空。

【问题讨论】:

  • if (cCustomer != null) 不起作用?
  • 附加调试器,看看什么是null?
  • cCustomer 是否已实例化或初始化?
  • @Tim (!(cCustomer == null)) 阅读起来太麻烦了。也许你想要 (cCustomer != null)
  • 如果cCustomer 为null,您将无法检查字段,因此您需要先查看包含对象(本例中为cCustomer)是否为null。如果不是,那么您可以检查各个属性。

标签: c# wpf silverlight mvvm


【解决方案1】:

您的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 属性是静态的吗?此外,在实例构造函数中为类设置静态属性可能是一种不好的做法,应该避免。

【讨论】:

  • 我已将该成员设为静态,因为我想在myViewModel 中访问我的Mainviewmodel 的当前实例。如果有任何方法可以访问 mainViewModel 的当前实例,请提出建议。
【解决方案2】:

您的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...
}

【讨论】:

  • 没那么容易。正如我在问题中提到的,我在 MainViewModel 的构造函数中调用 cCustomer = new Customer()。所以,cCustomer 永远不会为空。
  • 它可以为空,例如:var model = new MainViewModel(); model.cCustomer = null;。当然,您的调试器是一个很棒的工具,可以检查什么是空的,并在它变成空时设置断点。
【解决方案3】:

不要在那里这样做......这应该是您的数据模型的一部分。如果您的要求是不应该有 null 值,那么在类属性级别执行此操作:

public string Text
{
    get { return text; }
    set { if (value != null) { text = value; NotifyPropertyChanged("Text"); } }
}

【讨论】:

  • 我的要求不是不应该有空值。我想深入解释一下我的问题。我的项目中有 15 页。在主窗口上,我有一个框架和一个菜单,因此用户可以从一个页面导航到另一个页面,他们可能会在某些页面中填充值,甚至可能不会打开某些页面。当用户完成后,他/她必须点击保存按钮,这是保存更改的唯一方法,该按钮位于我的主窗口中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-11
  • 2017-08-11
  • 1970-01-01
相关资源
最近更新 更多