隐式转换:
不需要做任何工作,也不需要编写代码。
例:
var1=var2;
类型 | 可以显隐示转换为 |
byte | short,ushort,int,uint,long,ulong,float,double,decimal |
sbyte | short,int,long,float,double,decimal |
short | int,long,float,double,decimal |
ushort | int,uint,long,ulong,float,double,decimal |
int | long,ulong,double,decimal |
uint | long,ulong,float,double,decimal |
long | float,double,decimal |
ulong | float,double,decimal |
float | double |
char | ushort,int,uint,long,ulong,flaot,double,decimal |
显式转换:
就是强迫数据从一种类型转换为另一种类型。
语法:
(destinationType)sourceVar
注:如果把数据转换的目标数据类型不适合,那么将出现数据丢失或无法转换的情况出现。
用Convert显示转换方法:
如果使用Convert来转换数据类型,出现数据溢出现象将无法转换。
命令 结果
Convert.ToBoolean(val) val转换为bool
Convert.ToByte(val) val转换为byte
Convert.ToChar(val) val转换为char
Convert.ToDecimal(val) val转换为decimal
Convert.ToDouble(val) val转换为double
Convert.ToInt16(val) val转换为short
Convert.ToInt32(val) val转换为int
Convert.ToInt64(val) val转换为long
Convert.ToSByte(val) val转换为sbyte
Convert.ToSingle(val) val转换为float
Convert.ToString(val) val转换为string
Convert.ToUInt16(val) val转换为ushort
Convert.ToUInt32(val) val转换为uint
Convert.ToUint64(val) val转换为ulong
处理字符串的方法:
string.ToCharArray(); //将字符串输出为字符数组
string.ToLower(); //将字符串输出为大写字母
string.ToUpper(); //将字符串输出为小写字母
string.Trim(); //将字符串前后的空格删除
string.PadLeft(Int32); //右对齐此实例中的字符,在左边用空格填充以达到指定的总长度。
string.PadLeft (Int32, Char); //右对齐此实例中的字符,在左边用指定的 Unicode 字符填充以达到指定的总长度。
string.PadRight(Int32); //同理
string.split(char[]); //返回的字符串数组包含此实例中的子字符串
string.split(char[],Int32);
split方法的两个示例:
using System; public class SplitTest { public static void Main() { string words = "This is a list of words, with: a bit of punctuation" + "\tand a tab character."; string [] split = words.Split(new Char [] {' ', ',', '.', ':', '\t' }); foreach (string s in split) { if (s.Trim() != "") Console.WriteLine(s); } } } // The example displays the following output to the console: // This // is // a // list // of // words // with // a // bit // of // punctuation // and // a // tab // character
using System; public class StringSplit2 { public static void Main() { string delimStr = " ,.:"; char [] delimiter = delimStr.ToCharArray(); string words = "one two,three:four."; string [] split = null; Console.WriteLine("The delimiters are -{0}-", delimStr); for (int x = 1; x <= 5; x++) { split = words.Split(delimiter, x); Console.WriteLine("\ncount = {0,2} ..............", x); foreach (string s in split) { Console.WriteLine("-{0}-", s); } } } } // The example displays the following output: // The delimiters are - ,.:- // count = 1 .............. // -one two,three:four.- // count = 2 .............. // -one- // -two,three:four.- // count = 3 .............. // -one- // -two- // -three:four.- // count = 4 .............. // -one- // -two- // -three- // -four.- // count = 5 .............. // -one- // -two- // -three- // -four- // --