构造函数链创建对象,但在调用方中为null

时间:2019-12-21 19:28:45

标签: c#

这就是我所拥有的:

public partial class MainWindow : Window
    {
        IMainUIHandler MainUIHandler;
        public MainWindow()
        {
            //InitializeComponent();
            IMainUIHandler UIHandlerMain = new MainUIHandler();
            UIHandlerMain.PlayerMgtHandler.AddNewPlayer("2020", "_", 1, 3);
   ... more stuff
       }
    }

class MainUIHandler : IMainUIHandler
    {
        public IPlayerMgtUIHandler PlayerMgtHandler { get; }
        public MainUIHandler()
        {
            PlayerMgtHandler = new PlayerMgtUIHandler();
        }
    }

 class PlayerMgtUIHandler  : IPlayerMgtUIHandler 
    {
        public List<IPlayer> NewPlayers { get; } //TODO change List to HashSet

        public void AddNewPlayer(string idPrefix, string idSeparator, int idSeqNumber,int idNumDigits)
        {
            IPlayer player=new Player(idPrefix,idSeparator,idSeqNumber,idNumDigits);
            NewPlayers.Add(player);
        }

        public PlayerMgtUIHandler()
        {
            List<IPlayer> NewPlayers = new List<IPlayer>();
        }

    }

MainWindow开始,从IMainUIHandler UIHandlerMain = new MainUIHandler();开始,直到:

   public PlayerMgtUIHandler()
            {
                List<IPlayer> NewPlayers = new List<IPlayer>();

        }

List<IPlayer> NewPlayers并非一无所有;它有零个元素。当我退回到调用方PlayerMgtHandler.NewPlayers为null时。

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

class PlayerMgtUIHandler更改为:

   class PlayerMgtUIHandler  : IPlayerMgtUIHandler 
    {
        public List<IPlayer> NewPlayers { get; protected set; } //TODO change List to HashSet



        public void AddNewPlayer(string idPrefix, string idSeparator, int idSeqNumber,int idNumDigits)
        {
            IPlayer player=new Player(idPrefix,idSeparator,idSeqNumber,idNumDigits);
            NewPlayers.Add(player);
        }

        public PlayerMgtUIHandler()
        {
            NewPlayers = new List<IPlayer>();
        }

    }

现在它可以按我的意愿工作了。感谢您为我指出正确的方向。