Einzelnen Beitrag anzeigen

Dax
(Gast)

n/a Beiträge
 
#10

Re: [.NET] Generics und Operatorüberladung

  Alt 11. Jul 2009, 14:05
Wieso denn, das geht doch ganz fix

Code:
class Combiner<T>
{
   public Func<T, T, T> Add {
      get;
      private set;
   }

   public Combiner(Func<T, T, T> _add)
   {
      Add = _add;
   }
}

class MatrixFactory<T>
{
   Combiner<T> combiner;

   public MatrixFactory(Combiner<T> combiner)
   {
      this.combiner = combiner;
   }

   public Matrix<T> New(int dimX, int dimY)
   {
      return new Matrix<T>(combiner, dimX, dimY);
   }
}

class Matrix<T>
{
   Combiner<T> ops;
   T[] values;
   int dimX, dimY;

   public Matrix(Combiner<T> ops, int dimX, int dimY)
   {
      this.ops = ops;
      this.dimX = dimX;
      this.dimY = dimY;
      this.values = new T[dimX * dimY];
   }

   public T this[int x, int y]
   {
      get { return values[(y - 1) * dimY + (x - 1)]; }
      set { values[(y - 1) * dimY + (x - 1)] = value; }
   }

   public override string ToString()
   {
      string result = "";
      for (int y = 1; y <= dimY; y++) {
         if (y > 0)
            result += "\n";
         for (int x = 1; x <= dimX; x++) {
            if (x > 0)
               result += "\t";
            result += this[x, y].ToString();
         }
      }
      return result;
   }

   public static Matrix<T> operator +(T left, Matrix<T> right)
   {
      Matrix<T> result = new Matrix<T>(right.ops, right.dimX, right.dimY);
      result.values = new T[right.values.Length];
      for (int i = 0; i < result.values.Length; i++) {
         result.values[i] = right.ops.Add(left, right.values[i]);
      }
      return result;
   }

   public static Matrix<T> operator +(Matrix<T> left, Matrix<T> right)
   {
      Matrix<T> result = new Matrix<T>(right.ops, right.dimX, right.dimY);
      result.values = new T[right.values.Length];
      for (int i = 0; i < result.values.Length; i++) {
         result.values[i] = right.ops.Add(left.values[i], right.values[i]);
      }
      return result;
   }
}

public class MainClass
{
   public static void Main(string[] args)
   {
      MatrixFactory<double> mf = new MatrixFactory<double>(new Combiner<double>((a, b) => a + b));
      Matrix<double> m = mf.New(4, 4);
      Matrix<double> m2 = mf.New(4, 4);
      Random r = new Random();
      for (int x = 1; x <= 4; x++)
         for (int y = 1; y <= 4; y++)
            m2[x, y] = r.NextDouble();
      m = 1 + m2 + m;
      Console.WriteLine(m);
   }
}
  Mit Zitat antworten Zitat