正在使用数组初始值设定项

本文关键字:数组 | 更新日期: 2023-09-27 18:21:17

我有一个名为Matrix : IEnumerable<double>的类(经典的数学矩阵。它基本上是一个带有一些优点的2D数组)。

类是不可变的,因此在创建实例后无法更改其值。

如果想创建一个具有预先存在值的矩阵,我必须向构造函数传递一个数组,如下所示:

double[,] arr = new double[,]
{
    {1,2,3}, {4,5,6}, {7,8,9}
};
Matrix m = new Matrix(arr);

有没有办法把它变成这样:(?)

Matrix m = new Matrix
{
    {1,2,3}, {4,5,6}, {7,8,9}
};

更新:

找到了一种让它发挥作用的方法。我不确定这个解决方案是否可取,但它有效。

class Matrix : ICloneable, IEnumerable<double>
{
        // Height & Width are initialized in a constructor beforehand.
        /*
         * Usage:
         * var mat = new Matrix(3, 4)
         * {
         *              {1,2,3}, {4,5,6}, {7,8,9}, {10,11,12}
         * };
         */
        int rowIndex;
        bool allowArrayInitializer;
        double[,] tempData;
        double[,] data;
        public void Add(params double[] args)
        {
                if(!allowArrayInitializer)
                        throw new InvalidOperationException("Cannot use array initializer");
                if(args.Length != Width || rowIndex >= Height)
                        throw new InvalidOperationException("Invalid array initializer.");
                for(int i = 0; i < Width; i++)
                        tempData[i, rowIndex] = args[i];
                if(++rowIndex == Height)
                        data = tempData;
        }
}

正在使用数组初始值设定项

如果它是不可变的,则不是;句法糖是使用CCD_ 2来实现的。

您将无法通过初始值设定项进行初始化,但应该能够通过参数化构造函数进行初始化。您可以看到下面的示例代码:

class Matrix : IEnumerable<double>
{
    double[,] input;
    public Matrix(double[,] inputArray)
    {
        input = inputArray;
    }
    public IEnumerator<double> GetEnumerator()
    {
        return (IEnumerator<double>)input.GetEnumerator();
    }
    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return input.GetEnumerator();
    }
}

主要方法:

    static void Main(string[] args)
    {
        var m = new Matrix(new double[,] { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } });
    }

我希望这对你有帮助!

与其从IEnumerable派生,不如使用一个属性:

class Matrix 
{
        public double[,] Arr { get; set; }
}
Matrix m = new Matrix
{
      Arr = new double [,] { {1d,2d,3d}, { 4d,5d, 6d}}
};