如何以通用的方式处理数字? [英] How to handle numbers in a generic fashion?

查看:73
本文介绍了如何以通用的方式处理数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与写作泛型类处理内置类型,包括受到在类上处理矩阵操作的事实的启发。
尽管使用C#提出了这个问题,并且指出了泛型操作符



我不明白。 Java Number没有添加方法,因此您可以使用以下方法:

  public Number myAdd(Number a,Number b) {
return a.add(b);

$ / code>

那么如何处理一个你希望能够处理多个Java中的数字类型?

解决方案

基本问题是Java类型系统,它非常原始。 b
$ b

由于在Java中没有密封的类型概念(Java也没有可能像Haskell那样推断类型),所以没有办法使一个普通的Number + Number - >没有欺骗的数字。



对于原语(以及可以自动映射到它们的Integer等类型的对象)类型的提升,+操作是语言的一部分。 (这是问题的实际部分:a + b应该返回哪里a和b是不同类型的?)

如果你真的想要这种行为,必须找到(或创建)您自己的自定义类,使用反射或一系列(检查和)投射等。即使你使用泛型(记住泛型被类型擦除),铸造也需要完成。



我想这些问题是Number为何如此平淡的原因的一部分照原样。


My question is eerily similar to "Writing a generic class to handle built-in types" including being inspired by the fact of working on a class to handle operations on matrices. Although that question was asked using C# and pointed to an article on Generic Operators.

I don't get it. Java Number does not have an add method so you can have a method like:

public Number myAdd(Number a, Number b){
     return a.add(b);
}

So how do you handle a case where you want to be able to handle multiple types of Numbers in Java?

解决方案

The fundamental problem is with the Java type system which is very primitive.

Since there is no notion of a sealed set of types in Java (nor is it possible for Java to infer the types like Haskell does) there is no way to make make a general Number + Number -> Number without trickery.

For primitives (and those objects like Integer which can be automagically mapped to them) types promotion and the + operation is part of the language. (And this is actual part of the problem: what should Number a + Number b return where a and b are of different types?)

If you really want this behavior you'll have to find (or create) your own custom class that either uses reflection or a series (of checks and) casts and such. Even if you use generics (remember that generics are type-erased) casting will need to be done.

I imagine these problems are part of the reason why Number is as bland as it is.

这篇关于如何以通用的方式处理数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆