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

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

问题描述

说我想有一个接受任何数量的方法,有一个基类(或其他一些概念),我可以使用?

据我知道我必须让重载所有不同的数值类型(的Int32,Int16类型,字节,UInt32的,双,浮法,小数,等)。这似乎是非常乏味。如果不是这样,使用类型对象,并抛出异常,如果他们不可转换​​或分配给双 - 这是pretty糟糕,因为它意味着没有编译时检查

更新:
确定感谢您的意见,你是对的稻草人和Marc,实际上它声明为双实际上适用于所有除小数。

所以我一直在寻找的答案是双 - 它就像一个基类在这里,因为大多数的数字类型都分配给它。 (我猜是小数不分配给双,因为它可以得到太大了。)

 公共无效TestFormatDollars(){
INT I = 5;
字符串str = FormatDollars(I) // 还行吧
字节B = 5;
海峡= FormatDollars(B); // 还行吧
十进制D = 5;
海峡= FormatDollars(D); //这不能编译 - 十进制是不能分配给翻番
}公共静态字符串FormatDollars(双NUM){
回归$+ NUM;
}


解决方案

答案是:你不必为所有数值类型提供过载,只为双击十进制。所有其他(可能除了一些非常非常大的)将被自动转换为这些。

不是的基类的但实际上那是红鲱鱼。基类System.ValueType并没有多大帮助,因为它包含不在Numerics的类型。语言参考我在读什么是让我摆在首位困惑:)

(我只是在寻找的答案谁归因于,这是稻草人和Marc Gravell的组合,但因为他们的意见我已经把这里的答案)

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?

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.

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

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

解决方案

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.

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 :)

(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天全站免登陆