堆栈溢出错误在单例模式 [英] Stack overflow error in singleton pattern

查看:108
本文介绍了堆栈溢出错误在单例模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了单一模式。这是我的代码,当我调用Test.BuildData()函数时,我收到一个错误。请帮助

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

当我打电话时,我收到一个堆栈流错误Test.BuildData()函数。

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

推荐答案

尝试这样:

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

这篇关于堆栈溢出错误在单例模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆