8.2.2 Conversions

王朝other·作者佚名  2006-01-10
窄屏简体版  字體: |||超大  

8.2.2 Conversions

The predefined types also have predefined conversions. For instance,

conversions exist between the

predefined types int and long. C# differentiates between two kinds of

conversions: implicit conversions

and explicit conversions. Implicit conversions are supplied for conversions

that can safely be performed

without careful scrutiny. For instance, the conversion from int to long is

an implicit conversion. This

conversion always succeeds, and never results in a loss of information. The

following example

using System;

class Test

{

static void Main() {

int intValue = 123;

long longValue = intValue;

Console.WriteLine("{0}, {1}", intValue, longValue);

}

}

implicitly converts an int to a long.

In contrast, explicit conversions are performed with a cast expression. The

example

using System;

class Test

{

static void Main() {

long longValue = Int64.MaxValue;

int intValue = (int) longValue;

Console.WriteLine("(int) {0} = {1}", longValue, intValue);

}

}

uses an explicit conversion to convert a long to an int. The output is:

(int) 9223372036854775807 = -1

because an overflow occurs. Cast expressions permit the use of both

implicit and explicit conversions.

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有  導航