繁体   English   中英

对象被实例化但仍然收到警告:“字段'x'永远不会分配给...”

[英]Object is instantiated but still getting Warning: “Field 'x' is never assigned to …”

描述

我想我声明并实例化了这个类:_teamsVM,但我不断得到警告,引用:

字段'Sta​​rtpageVM2._teamsVM'永远不会分配给,并且始终将其默认值设置为null。

另外 :在运行应用程序时,它确实给了我一个错误,这个类没有被实例化(证明VS2017在某种程度上是正确的)。

问题我错过了什么?

环境:

  • Microsoft Visual Studio 2017
  • 项目类型:通用Windows

以下是涉及的4个类的代码。

基类视图模型:

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;
        }
    }
}

在构造函数中,您永远不会分配成员变量,而是在构造函数的范围内创建一个新变量:

#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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM