Writing a generic class to handle built-in types

2019-07-15 12:02发布

问题:

Not too practical maybe, but still interesting.

Having some abstract question on matrix multiplication I have quickly implemented a matrix for ints, then tested my assumptions.

And here I noticed that just int matrix is not good, if I occasionally want to use it with decimal or double. Of course, I could try just to cast all to double, but that's not convenient way.

Continue with assumption we could have a bunch of objects we are able to add and multiply - why don't use them in my matrix?

So, just after considering it would be a Matrix class now I faced that generic T could not be used, I need it to support some interface which could add and multiply.

And the problem is I could override operators in my class, but I could not introduce an interface which would support operators. And I have an operators in built-in types, but still no interface over them.

What would you do in such a case considering you do not want to duplicate worker class body? Wrappers and implicit casting didn't help me much, I'm interested in a beautiful solution.

Thanks.

回答1:

For this you need generic maths. Luckily I have done this. Usage would be similar to this "complex" (i.e. x+iy) example. The Operator class is now part of MiscUtil.



回答2:

Well, there is a less tech-heavy way to do just that. You cannot add a new interface for "int" or "double". But you can declare an interface for an object that can multiply and add values of some generic type. And then you can implement the interface for all the types you need:

public interface ICalculator<T>
{

   T Add(T x, T y);
   T Multiply(T x, T y);

}

public class MatrixMultiplier<T>
{

  public MatrixMultiplier(ICalculator<T> calculator) { ... }

}

public class IntCalculator : ICalculator<int>
{

  public int Add(int x, int y)
  {
    return x + y;
  }

  public int Multiply(int x, int y)
  {
    return x * y;
  }

}