如何使用带参数的构造函数初始化对象数组

本文关键字:初始化 对象 数组 构造函数 何使用 参数 | 更新日期: 2023-09-27 18:13:22

我正在尝试为游戏生成方程式。

我为方程中的每一项创建了一个类:

[System.Serializable]
public class EquationTerm
{
    public int Value { get; set; }      //random int between 1 and 9
    public int Sign { get; set; }       //1 for +, 2 for -, 3 for *, 4 for / 
    public bool IsNextTerm { get; set; }
    //default positive equationTerm 
    public EquationTerm(int value)
    {
        Value = value;
        Sign = 1;
        IsNextTerm = false;
    }
    public EquationTerm(int value, int sign, bool nextTerm)
    {
        Value = value;
        Sign = sign;
        IsNextTerm = nextTerm;
    }
}

然后创建两个数组来保存等式的左边和右边。我想使用InitializeArray函数来使用我的构造函数生成两个数组,但我不能使用它们,因为它们都有参数。有别的办法吗?

public class EquationGenerator : MonoBehaviour
{
    EquationTerm[] LeftTerms;
    EquationTerm[] RightTerms;
    void Start ()
    {
        //Initialize both side with a random number of terms
        LeftTerms = InitializeArray<EquationTerm>(Random.Range (1, 6));
        RightTerms = InitializeArray<EquationTerm>(Random.Range (1, 6));
    }
    EquationTerm[] InitializeArray<EquationTerm>(int length) where EquationTerm : new()
    {
        EquationTerm[] array = new EquationTerm[length];
        array [0] = new EquationTerm (Random.Range (1, 10));
        for (int i = 1; i < length; ++i)
        {
            array[i] = new EquationTerm (Random.Range (1, 10), Random.Range (1, 5), true);
        }
        return array;
    }

我在另一篇文章中看到我可以使用Activator。创建实例,所以我试着写

array[0] = (EquationTerm)Activator.CreateInstance(typeof(EquationTerm), new object[] { EquationTerm (Random.Range (1, 10)) });

但是它告诉我Activator不存在

如何使用带参数的构造函数初始化对象数组

何不试试非通用版本:

public class EquationGenerator 
        {
            EquationTerm[] LeftTerms;
            EquationTerm[] RightTerms;
            void Start()
            {
                //Initialize both side with a random number of terms
                LeftTerms = InitializeArray(Random.Range(1, 6));
                RightTerms = InitializeArray(Random.Range(1, 6));
            }
            EquationTerm[] InitializeArray(int length)
            {
                EquationTerm[] array = new EquationTerm[length];
                array[0] = new EquationTerm(Random.Range(1, 10));
                for (int i = 1; i < length; ++i)
                {
                    array[i] = new EquationTerm(Random.Range(1, 10), Random.Range(1, 5), true);
                }
                return array;
            }
        }