什么是“基类"?对于 C# 数值类型? [英] What is the "base class" for C# numeric value types?

查看:24
本文介绍了什么是“基类"?对于 C# 数值类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想要一个接受任何类型数字的方法,是否有我可以使用的基类(或其他概念)?

Say I want to have a method that takes any kind of number, is there a base class (or some other concept) that I can use?

据我所知,我必须对所有不同的数字类型(Int32、Int16、Byte、UInt32、Double、Float、Decimal 等)进行重载.这看起来非常乏味.要么使用对象"类型,如果它们不可转换或不可分配给双精度值,则抛出异常 - 这很糟糕,因为它意味着没有编译时检查.

As far as I know I have to make overloads for all the different numeric types (Int32, Int16, Byte, UInt32, Double, Float, Decimal, etc). This seems awfully tedious. Either that or use the type "object" and throw exceptions if they are not convertable or assignable to a double - which is pretty bad as it means no compile time checking.

更新:好的,感谢您的评论,您是对的 Scarecrow 和 Marc,实际上将其声明为 Double 实际上适用于除 Decimal 之外的所有对象.

UPDATE: OK thanks for the comments, you are right Scarecrow and Marc, in fact declaring it as Double actually works for all except Decimal.

所以我正在寻找的答案是 Double - 它在这里就像一个基类,因为大多数数字类型都可以分配给它.(我想 Decimal 不能分配给 Double,因为它可能会变得太大.)

So the answer I was looking for is Double - it acts like a base class here since most numeric types are assignable to it. (I guess Decimal is not assignable to Double, as it could get too big.)

public void TestFormatDollars() {
    int i = 5;
    string str = FormatDollars(i);   // this is OK
    byte b = 5;
    str = FormatDollars(b);     // this is OK
    decimal d = 5;
    str = FormatDollars(d);     // this does not compile - decimal is not assignable to double
}

public static string FormatDollars(double num) {
    return "$" + num;
}

推荐答案

答案是:您不需要为所有数字类型提供重载,只需为 DoubleDecimal.所有其他的(可能除了一些非常大的)将自动转换为这些.

The answer is: you don't need to provide overloads for ALL the numeric types, just for Double and Decimal. All others (except maybe some very unusually large ones) will be automatically converted to these.

不是基类,但实际上那是红鲱鱼.基类 System.ValueType 没有多大帮助,因为它包含非数字类型.我正在阅读的语言参考首先让我感到困惑:)

Not a base class but in fact that was the red herring. The base class System.ValueType doesn't help much as it includes types that are not numerics. The language reference i was reading was what got me confused in the first place :)

(我只是在寻找将答案归因于谁,它是稻草人和 Marc Gravell 的组合,但由于他们是评论,我将答案放在这里)

(I was just looking for who to attribute the answer to and it was a combination of Scarecrow and Marc Gravell, but since they were comments i have put the answer here)

这篇关于什么是“基类"?对于 C# 数值类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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