2

我有一个名为Matrix : IEnumerable<double>, 的类(经典的数学矩阵。它基本上是一个带有一些好东西的二维数组)。

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

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

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

更新:

找到了一种 hack-ish 方式来让它工作。我不确定这个解决方案是否可取,但它确实有效。

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

3 回答 3

5

如果它是不可变的,则不是;该语法糖是使用Add().

于 2013-07-07T16:08:29.250 回答
0

您将无法通过初始化程序执行此操作,但应该能够通过参数化构造函数执行此操作。您可以看到下面的示例代码:

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

我希望这可以帮助你!

于 2013-07-07T16:56:26.167 回答
0

而不是派生自我IEnumerable 会使用一个属性:

class Matrix 
{
        public double[,] Arr { get; set; }
}

Matrix m = new Matrix
{
      Arr = new double [,] { {1d,2d,3d}, { 4d,5d, 6d}}
};
于 2014-02-10T16:38:27.313 回答