}
它的运行结果是
The ASCII code of 'a' is: 97
ASCII is 65, the char is: A
The Unicode of '中' is: 20013
Unicode is 22478, the char is: 城
从这个例子中,我们便能非常清楚的了解――通过强制转换,可以得以字符的编码,或者得到编码表示的字符。如果你需要的不是 short 型的编码,请参考第 1 条进行转换,即可得到 int 等类型的编码值。
4. 数值字符串和数值之间的转换
首先,我们得搞明白,什么是数值字符串。我们知道,在 C# 中,字符串是用一对双引号包含的若干字符来表示的,如 "123"。而 "123" 又相对特殊,因为组成该字符串的字符都是数字,这样的字符串,就是数值字符串。在我们的眼中,这即是一串字符,也是一个数,但计算机却只认为它是一个字符串,不是数。因此,我们在某些时候,比如输入数值的时候,把字符串转换成数值;而在另一些时候,我们需要相反的转换。
将数值转换成字符串非常简单,因为每一个类都有一个 void ToString() 方法。所有数值型的 void ToString() 方法都能将数据转换为数值字符串。如 123.ToSting() 就将得到字符串 "123"。
那么反过来,将数值型字符串转换成数值又该怎么办呢?我们仔细查找一下,会发现 short, int, float 等数值类型均有一个 static Parse() 函数。这个函数就是用来将字符串转换为相应数值的。我们以一个 float 类型的转换为例: float f = float.Parse("543.21"); 其结果 f 的值为 543.21F。当然,其它的数值类型也可以使用同样的方法进行转换,下面的例子可以更明确的说明转换的方法:
private void TestStringValue() {
float f = 54.321F;
string str = "123";
this.textBox1.Text = "";
this.textBox1.AppendText("f = "+ f.ToString() + "\n");
if (int.Parse(str) == 123) {
this.textBox1.AppendText("str convert to int successfully."); } else {
this.textBox1.AppendText("str convert to int failed.");
}
}
运行结果:
f = 54.321
str convert to int successfully.
5. 字符串和字符数组之间的转换
字符串类 System.String 提供了一个 void ToCharArray() 方法,该方法可以实现字符串到字符数组的转换。如下例:
private void TestStringChars() {
string str = "mytest";
的转换、十六进制数输出以及日期型数据的一些转换处理... byte -> System.Byte char -> System.Char ... float e = d; double f = e; this.textBox1...
是系统默认的转换, 其本质是小存储容量数据类型自动转换为大存储容量 数据类型。...从 double 到 sbyte,byte,short,ushort,int,uint,long,ulong,char,float,或 ...
C#数据类型转换方法_计算机软件及应用_IT/计算机_专业资料。C#数据类型转换方法...decimal ulong float,double,decimal float double char ushort,int,uint,long,...
为布尔型boolean;字符型char;整型byte、short、int、long;浮点型float、double。...在进行简单数据类型之间的转换(自动转换或强制转换)时,我们总是可以利用包装类...
(byte); 引用类型)的值转换为 int 类 public static int ToInt32(char); ...C# 也不例外,其基本数据类型有 int,short,long,float,double,string 等。数据...
double 型之间的转换,整数和 String 类型之间的转换,以及处理、显 示时间方面的...(byte,short,char)--int--long--float--double[/center] 简单数据类型之间的...
int,char long ulong float double decimal byte,sbyte,short,ushort,int,uint,...显示转换,都只 是从一种数值类型(包括char类型)转换到 另一种数值类型的转换...
float -> System.Single (单精度浮点型,占 4 个字节) double -> System....byte a = 1; char b = 'a'; short c = 1; int d = 2; long e ...
( byte 、 short 、 char )——int——long——float——double PS:此处的“...包装数据类型与基本数据类型之间的转换简单类型的变量转换为相应的包装类,可以利用...
false char 数据类型有:unicode 字符,16 位 对应的类类型:Integer,Float,Boolean,Character,Double,Short,Byte, Long 转换原则 从低精度向高精度转换 byte ,short...
热门文档