Stack overflow error in singleton pattern

删除回忆录丶 提交于 2019-12-25 02:22:04

问题


I have implemented Single Pattern. Here is my code i am getting the an error when i call the Test.BuildData() function. Please help

 public class WordDataItem
    {
        public string Word { get; set; }
        public string Definition { get; set; }
        public int WordGroupKey { get; set; }
    }

    public class WordDataGroup
    {
        public List<WordDataItem> listItem = new List<WordDataItem>(); 
        public int GroupKey { get; set; }
    }
    public sealed class WordDataSource
    {
        private static  WordDataSource _dataSoruce;

        private List<WordDataGroup> listGroup = new List<WordDataGroup>();

        public List<WordDataGroup> ListGroup
        {
            get { return listGroup; }
            set { listGroup = value; }
        }

        private WordDataSource() { }

        public static WordDataSource Instance
        {
            get
            {
                if (Instance == null)
                {
                    _dataSoruce = new WordDataSource();
                }
                return _dataSoruce;
            }
        }        
    }

    public static class Test
    {
        public static void BuildData()
        {
             WordDataSource.Instance.ListGroup.Add(new WordDataGroup() { GroupKey = 8, listItem = new List<WordDataItem>() { new WordDataItem() {Word = "Hello", Definition="Greetings", WordGroupKey = 8}} });
        }
    }

I get an error of stack over flow when i call the Test.BuildData() function.


回答1:


Your Instance property is recursively calling into itself when you check if it is null.




回答2:


Try this:

public static WordDataSource Instance
{
    get
    {
        if (_dataSoruce == null)
        {
            _dataSoruce = new WordDataSource();
         }
         return _dataSoruce;
     }
}


来源:https://stackoverflow.com/questions/13545063/stack-overflow-error-in-singleton-pattern

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!