使用List中的构造函数填充类的变量

时间:2018-06-14 08:25:13

标签: c#

这听起来很简单,但我想我错过了一些东西。

我有以下课程:

 public class Difficulty
    {

        public int Fractional;
        public int ArtistMax;

        private readonly List<Difficulty> QuestionDifficultyList = new List<Difficulty>();

        public Difficulty()
        {
            PopulateDifficultyData();
        }
        public void PopulateDifficultyData()
        {
            Difficulty item = new Difficulty
            {
                Fractional = 3,
                ArtistMax = 30
            };
            QuestionDifficultyList.Add(item);
         }
    }

调用初始化类时:

  Difficulty DifficultyData = new Difficulty();

它会无休止地执行构造函数。

这种情况应该采用什么方法? 我需要使用一些值填充类List。

4 个答案:

答案 0 :(得分:0)

使用new初始化实例时,您正在调用类构造函数。您在PopulateDifficultyData()构造函数中调用Difficulty(),这会创建新的Difficulty实例。新实例创建再次调用Difficulty()构造函数,依此类推,在某种无限循环中。

您需要在其他位置创建新实例,例如main或某个经理类。

答案 1 :(得分:0)

您无需在构造函数中创建新的Difficulty实例。

public class Difficulty
{

    public int Fractional;
    public int ArtistMax;

    private readonly List<Difficulty> QuestionDifficultyList = new List<Difficulty>();

    public Difficulty()
    {
        PopulateDifficultyData();
    }
    public void PopulateDifficultyData()
    {
            Fractional = 3,
            ArtistMax = 30
     }
}

此外,您正在为每个难度实例创建一个QuestionDifficultyList - 您真的想要这样做吗?也许这应该是静态的,所以你只有一个列表。

答案 2 :(得分:0)

在我看来,最简单的解决方案是在PopulateDifficultyData中使用不同的构造函数。像这样:

    public Difficulty(int fractional, int artistMax)
    {
       Fractional = fractional;
       ArtistMax = artistMax;
    }
    public void PopulateDifficultyData()
    {
        Difficulty item = new Difficulty(3, 30);

        // continue to use item
     }

答案 3 :(得分:0)

此代码将列表放在另一个类中,使Difficulty类更具动态性。它仍然可以自动创建一个新的难度实例:

public class Difficulty
{
    public int Fractional;
    public int ArtistMax;

    public Difficulty()
    {
        PopulateDifficultyWithDefaultData();
    }

    public Difficulty(int fractional, int artistmax)
    {
        this.Fractional = fractional;
        this.ArtistMax = artistmax;
    }

    public void PopulateDifficultyWithDefaultData()
    {
        this.Fractional = 3,
        this.ArtistMax = 30
    }
}

public class DifficultyList
{
    public List<Difficulty> QuestionDifficultyList = new List<Difficulty>();

    public void AddDifficulty()
    {
        QuestionDifficultyList.Add(new Difficulty());
    }

    public void AddDifficulty(int fractional, int artistmax)
    {
        QuestionDifficultyList.Add(new Difficulty(fractional, artistmax));
    }
}