---------------------- <a href="http://edu.csdn.net"target="blank">ASP.Net+Android+IO开发S</a>、<a href="http://edu.csdn.net"target="blank">.Net培训</a>、期待与您交流! ----------------------
C#中类型转换分为,隐式转换、显示转换、用户自定义数据类型转换。
隐式转换:不需要指定转换类型,通过接收类型来进行自动转换。一般是低类型向高类型转化,能够保证值不发生变化。
显示转换:为需要转换的数据类型指定其要转换成的类型,也称强制类型转换。不能保证数据的正确性。
用户自定义数据类型转换:所有的用户自定义转换都是静态的,要使用static关键字
用户自定义转换分显示和隐示,它们用implicit(隐式转换)或 explicit(显示转换)关键字声明。
static 访问修辞符 转换修辞符 operator 转换类型(参数)
C#中显示转换调用:
1、Convert.ToInt32(); //转换成32位的整数。
int in = Convert.ToInt32("32");
//把字符串32转换成 int类型 用法:Convert.To(Int32转换后的类型)(需转换数据)
2、变量.ToString();/最常见的转换成 字符串
例:
int b =123123;
b.ToString(); //得到B的字符串类型 "123123"
3、"转换"+1158 //后面的数字会转换为字符串。
string str = "kbs"+1158; //得到str字符串 "kbs1158"
4、((类型x)变量 k) //强行将 k 转换成 X类型
例:
int k = 123;
string st = (string)k; //把 k 强制转换成 string 类型
5、int.Parse(string);把字符串型转换成其他类型。
int in = int.Parse(3.22); //把 3.22转换成 int 类型
6、还有,如果要转换成的类型为引用类型,还可以用 as
as 运算符用于执行引用类型的显式类型转换。 如果要转换的类型与指定类型兼容,转换就会成功;
如果类型不兼容,则返回null,并且不会引发异常
例:
object st=”SomeString”;
object si=5;
string si=st as string;//类型兼容si=”SomeString”
string st=si as string;//类型不兼容st=null
从 sbyte 到 short、int、long、float、double 或 decimal 。
从byte 到short、ushort、int、uint、long、ulong、float double 或 decimal。
从short到 int、long、float、double 或 decimal。
从ushort到int、uint、long、ulong、float、double 或 decimal。
从int 到long、float、double 或 decimal。
从uint到 long、ulong、float、double 或 decimal。
从long到float、double 或 decimal。
从ulong到float、double 或 decimal。
从char到ushort、int、uint、long、ulong、float、double 或 decimal。
从float到 double。
不存在向 char 类型的隐式转换,因此其它整型的值不会自动转换为 char 类型。
浮点型不能隐式地转化为decimal型
---------------------- <a href="http://edu.csdn.net"target="blank">ASP.Net+Android+IOS开发</a>、<a href="http://edu.csdn.net"target="blank">.Net培训</a>、期待与您交流! ----------------------
详细请查看:<a href="http://edu.csdn.net" target="blank">http://edu.csdn.net</a>