0

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

 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() 函数时出现堆栈溢出错误。

4

2 回答 2

2

当您检查它是否为空时,您的 Instance 属性会递归调用自身。

于 2012-11-24T20:13:33.293 回答
2

尝试这个:

public static WordDataSource Instance
{
    get
    {
        if (_dataSoruce == null)
        {
            _dataSoruce = new WordDataSource();
         }
         return _dataSoruce;
     }
}
于 2012-11-24T20:15:01.680 回答