简体   繁体   English

编写通用类以处理内置类型

[英]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. 在这里,我注意到,如果我偶尔想将其与十进制或双精度型一起使用,那么仅使用int矩阵是不好的。 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. 因此,在考虑到现在将是一个Matrix类之后,我面对无法使用通用T的问题,我需要它来支持一些可以相乘和相乘的接口。

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 . 用法将类似于此“复杂”(即x + iy) 示例 The Operator class is now part of MiscUtil . 现在,Operator类是MiscUtil的一部分。

Well, there is a less tech-heavy way to do just that. 好吧,有一种技术含量较低的方法可以做到这一点。 You cannot add a new interface for "int" or "double". 您不能为“ int”或“ 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;
  }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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