加宽和缩小转换 [英] Widening and Narrowing Conversions
问题描述
在技术测试中有人问我这个问题,我想知道它的答案
如果您有2个变量,一个是int,另一个是double,那么您想将其中一个变量转换为另一个变量,您将选择将哪个变量转换为变量,为什么?"
i had been asked this question in a technical test and i want to know it''s answer
''if you have 2 variables one is int and the other is double you want to make casting for one of the variables to the other one which one will you choose to cast to and why ?''
推荐答案
int
是4bytes
,而double
是8bytes
在c#
强制转换意味着将变量的一些位裁剪以使其适合较小值变量的位桶,从而剥离一些值以适合目标变量的类型(适用于原始类型变量)
因此,在这种情况下,如果我们具有以下两个变量:
int
is of 4bytes
, and,double
is of 8bytes
in c#
Casting means cropping some bits of a variable to fit a it''s value into a smaller sized variable''s bucket of bits and hence stripping off some value to fit the type of the target variable (Applicable for primitive type variables)
So, in this case, if we have the following two variables:
int a;
double d = 2.567;
如果要将变量double
变量d
分配给int
变量a
,则需要将其转换为int
.
we would need to cast the double
variable d
to an int
if we want to assign it to the int
variable a
.
a = (int)d; // a would have value assigned to 2 in this case.
因此,这里的转换为"narrowing conversion"
,因为8 bytes
的二进制值表示形式无法放入4 byte
变量中.
但是,如果需要按如下所示将int
值分配给double
变量,则不需要任何强制转换:
So, casting is a "narrowing conversion"
here as the binary value representations of 8 bytes
cannot fit into a 4 byte
variable.
However, if we need to assign an int
value to a double
variable as follows, we wouldn''t require any casting:
int a = 5;
double d;
d = a; // d would have value assigned to 5.0
这是一个"widening conversation
",因为4 bytes
的二进制值表示形式已分配给8 byte
变量.
This is a "widening conversation
" as the binary value representations of 4 bytes
are being assigned to a 8 byte
variable.
您通常不会基于变量类型''.通常,您会根据问题要求"进行投放(如果无法避免的话).
:)
You usually don''t choose ''based on the variable type''. You usually cast (if you cannot avoid it) based on the problem ''requirements''.
:)
这篇关于加宽和缩小转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!