描述
我想我声明并实例化了这个类:_teamsVM,但我不断得到警告,引用:
字段'StartpageVM2._teamsVM'永远不会分配给,并且将永远分配 将其默认值设为null。
同样:在运行应用程序时,它确实给了我一个错误,这个类没有实例化(证明VS2017在某种程度上是正确的)。
问题 我错过了什么?
环境:
代码
以下是涉及的4个类的代码。
基类viewmodel:
using System.ComponentModel;
namespace MyApp.ViewModels
{
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
主Viewmodel(包含警告):
using System.Collections.ObjectModel;
using MyApp.Models;
namespace MyApp.ViewModels
{
public class StartPageVM2 : BaseViewModel
{
#region Declarations
private TeamsVM2 _teamsVM;
public ObservableCollection<Team2> Teams {
get { return _teamsVM.Teams; }
set { _teamsVM.Teams = value; }
}
#endregion Declarations
#region Constructor
public StartPageVM2()
{
TeamsVM2 _teamsVM = new TeamsVM2();
}
#endregion
}
}
子视图模型:
using MyApp.Models;
using System.Collections.ObjectModel;
namespace MyApp.ViewModels
{
public class TeamsVM2 : BaseViewModel
{
private ObservableCollection<Team2> _teams;
public ObservableCollection<Team2> Teams {
get { return _teams; }
set { _teams = value; }
}
public TeamsVM2()
{
ObservableCollection<Team2> _teams = new ObservableCollection<Team2>();
}
}
}
使用的Model类:
namespace MyApp.Models
{
public class Team2
{
private string _sTeamName;
public string TeamName {
get { return _sTeamName; }
set { _sTeamName = value; }
}
public Team2() { }
public Team2(string sTeamName)
{
_sTeamName = sTeamName;
}
}
}
答案 0 :(得分:3)
在构造函数中,您永远不会分配成员变量,而是在构造函数的范围内创建一个新变量:
#region Constructor
public StartPageVM2()
{
TeamsVM2 _teamsVM = new TeamsVM2();
}
#endregion
注意范围。那时_teamsVM != this._teamsVM
请改为关注:
#region Constructor
public StartPageVM2()
{
_teamsVM = new TeamsVM2(); //or write this._teamsVM = new TeamsVM2(); to highlight the scope
}
#endregion