How to implement a pure custom object initializer for the Matrix class

I have a custom Matrix class that I would like to implement a custom object initializer, similar to what double [,] can use, but cannot figure out how to implement it.

Ideally, I would like it to look like

 var m1 = new Matrix { { 1.0, 3.0, 5.0 }, { 7.0, 1.0, 5.0 } }; 

at the moment I have a regular constructor with a signature

 public Matrix(double[,] inputArray){...} 

which accepts a challenge like this

 var m1 = new Matrix(new double[,] { { 1.0, 3.0, 5.0 }, { 7.0, 1.0, 5.0 } }); 

and an intializer object that takes the next use, inheriting the IEnumerable<double[]> interface and implementing the public void Add(double[] doubleVector)

 var m2 = new Matrix { new [] { 1.0, 3.0, 5.0 }, new [] { 7.0, 1.0, 5.0 } }; 

when I try to use the intializer object, I would like to get a compiler error without having an overload for Add , which takes X the number of arguments, where X is the number of columns I'm trying to create (i.e., in my example 3 are given).

How can I configure my class to accept an argument as I pointed out?

+5
source share
1 answer

define an Add method with the params and ignore the end element in an array that is longer than the width of the matrix

 public void Add(params double[] doubleVector) { // code } 

if the array is shorter, the default elements remain ( 0 )

 // sample var M = new Matrix() { { 1.2, 1.0 }, { 1.2, 1.0, 3.2, 3.4} }; 
+5
source

Source: https://habr.com/ru/post/1234692/


All Articles