C#中的隐式数据转换 [英] implicit data conversion in c#

查看:117
本文介绍了C#中的隐式数据转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将一种类型的数据分配给另一种类型时,如果
,则将自动进行隐式转换
1>两种类型兼容

2>目标类型的范围大于源类型.
(来自c#4.0的完整参考.作者:Herbert Schildt)

请通过简单的示例告诉我第一条规则的含义.

When one type of data is assigned to another type an implicit conversion will take place automatically if

1>The two types are compatible

2>Destination type has a range that is greater than sourse type.
(reference from c# 4.0 complete reference.by Herbert Schildt)

Plese tell me meaning of first rule with simple example.

推荐答案

^ ]您拥有所需的一切.
一个简单的例子":
Here[^] you have all you need.
A ''simple example'':
int i = 5;
double f = i;


int num =  2147483647;
long bigNum = num;








or

class Alpha
{
int data1;
int data2;

public static implicit Alpha(int n)
     {
     Alpha a=new Alpha();
     a.data1=n;
     return a;       //here the value of n fully becomes  part of the destination. ie. no data loss.
     }


public static explicit int(Alpha a)
     {
     return a.data1;  // here only data1 is returned. and data2 is   lost because of the conversion

     }

}





您可以按以下方式访问数据.


Alpha = 25; //隐式转换-不强制转换

//int n = a; //错误-没有强制转换

int n =(int)a; //显式转换-使用强制转换





You can access the data as follows.


Alpha a = 25; //implicit conversion - no casting

//int n = a; // ERROR - without casting

int n = (int) a; //explicit conversion - with casting




这意味着如果您有两壶水,一壶装5升水,另一壶装2升水,则可以将2升壶水倒入5升壶中.

同样,请查看以下来自MSDN的示例
Hi,

it means if you have two jug of water, one with 5 liter and another with 2 liter then you can pour 2 liter jug liquid into 5 liter jug.

Similarly Please look into below example from MSDN
Digit d = new Digit(3);
// implicit (no cast) conversion from Digit to byte
byte b = d;


在上面的示例中,您可以看到,我们可以将Digit d的值复制到字节b中.无需显式转换.这就是第一阶段的含义.

谢谢.


In above example you can see, we can copy the value of Digit d into byte b. without explicitly casting. this is what the meaning of first phase.

Thanks.


这篇关于C#中的隐式数据转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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