简体   繁体   中英

Writing a generic class to handle built-in types

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.

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

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

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM