[英]Object is instantiated but still getting Warning: “Field 'x' is never assigned to …”
Description 描述
I think I declare and instantiate the class: _teamsVM, but I keep getting the waring, quote: 我想我声明并实例化了这个类:_teamsVM,但我不断得到警告,引用:
Field 'StartpageVM2._teamsVM' is never assigned to, and will Always have its default value null. 字段'StartpageVM2._teamsVM'永远不会分配给,并且始终将其默认值设置为null。
Also : when running the application, it indeed gives me an error that this class is not instantiated (proving VS2017 is somehow right). 另外 :在运行应用程序时,它确实给了我一个错误,这个类没有被实例化(证明VS2017在某种程度上是正确的)。
Question What am I missing?? 问题我错过了什么?
Environment: 环境:
Code 码
Here below is the code of the 4 classes involved. 以下是涉及的4个类的代码。
The base class 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));
}
}
}
}
The main Viewmodel (containing the warning): 主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
}
}
The sub viewmodel: 子视图模型:
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>();
}
}
}
And the Model class used: 使用的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;
}
}
}
In your Constructor you never assign the member variable but create a new variable within the scope of the constructor: 在构造函数中,您永远不会分配成员变量,而是在构造函数的范围内创建一个新变量:
#region Constructor
public StartPageVM2()
{
TeamsVM2 _teamsVM = new TeamsVM2();
}
#endregion
beware the scope. 注意范围。 at that point _teamsVM != this._teamsVM
那时_teamsVM != this._teamsVM
Do following instead: 请改为:
#region Constructor
public StartPageVM2()
{
_teamsVM = new TeamsVM2(); //or write this._teamsVM = new TeamsVM2(); to highlight the scope
}
#endregion
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.