2006-11-21

C#.NET 中的类型转换

来源: 本站收集整理 作者:佚名 评论 0 条
 "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";

    char[] chars = str.ToCharArray();

    this.textBox1.Text = "";

    this.textBox1.AppendText("Length of "mytest" is "   str.Length   "n");

    this.textBox1.AppendText("Length of char array is "   chars.Length   "n");

    this.textBox1.AppendText("char[2] = "   chars[2]   "n");

}

  例中以对转换转换到的字符数组长度和它的一个元素进行了测试,结果如下:

Length of "mytest" is 6
Length of char array is 6
char[2] = t

  可以看出,结果完全正确,这说明转换成功。那么反过来,要把字符数组转换成字符串又该如何呢?
  我们可以使用 System.String 类的构造函数来解决这个问题。System.String 类有两个构造函数是通过字符数组来构造的,即 String(char[]) 和 String[char[], int, int)。后者之所以多两个参数,是因为可以指定用字符数组中的哪一部分来构造字符串。而前者则是用字符数组的全部元素来构造字符串。我们以前者为例,在 TestStringChars() 函数中输入如下语句:

char[] tcs = {'t', 'e', 's', 't', ' ', 'm', 'e'};
string tstr = new String(tcs);
this.textBox1.AppendText("tstr = "" tstr ""n");

  运行结果输入 tstr = "test me",测试说明转换成功。
  实际上,我们在很多时候需要把字符串转换成字符数组只是为了得到该字符串中的某个字符。假如只是为了这个目的,那大可不必兴师动众的去进行转换,我们只需要使用 System.String 的 [] 运算符就可以达到目的。请看下例,再在 TestStringChars() 函数中加入如如下语名:
共10页: 上一页 [1] [2] [3] [4] 5 [6] [7] [8] [9] [10] 下一页

(本文仅表明作者个人观点,不代表本站及其管理员立场.) 推荐 收藏 投稿 打印 返回 关闭
上一篇:登陆页优化的七大规则  
下一篇:ASP.NET 2.0高级数据处理之主从数据表
    评论加载中…
 推荐文章
     

网站首页  -  网站地图 -   站长论坛  -  网站投稿  -    -  网站管理
Copyright © 2008 芜湖站长站 All Rights Reserved 皖ICP备07500611号