将字符串转换为相应数值

将数值转换成字符串非常简单,因为每一个类都有一个 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.

 
C#简单变色龙游戏 /// /// 创建一副52张的新牌 /// /// public static System.Collections.ArrayList Creat() { System.Collections.ArrayList list = new System.Collections.ArrayList(); for (int i = 3; i <= 6; i++) { for (int j = 1; j <= 13; j++) { Poker p = new Poker(); switch (j) { case 1: p = new Poker((PokerStyle)i, "A", j, 11); break; case 2: p = new Poker((PokerStyle)i, j.ToString(), j, 10); break; case 11: p = new Poker((PokerStyle)i, "J", j, 11); break; case 12: p = new Poker((PokerStyle)i, "Q", j, 2); break; case 13: p = new Poker((PokerStyle)i, "K", j, 3); break; default: p = new Poker((PokerStyle)i, j.ToString(), j, j); break; } list.Add(p); } } return list; } /// /// 洗牌 /// /// /// public static System.Collections.ArrayList shuffle(System.Collections.ArrayList list)//洗牌 { System.Random r = new Random(); for (int i = 0; i <= 7; i++) { int rightOrRight = r.Next(1, 3); Poker[] leftPoker = new Poker[list.Count / 2]; Poker[] rightPoker = new Poker[list.Count % 2 == 0 ? list.Count / 2 : list.Count / 2 + 1]; list.CopyTo(0, leftPoker, 0, list.Count / 2); list.CopyTo(list.Count / 2, rightPoker, 0, list.Count % 2 == 0 ? list.Count / 2 : list.Count / 2 + 1); if (rightOrRight == 1)//左边插右边 { list.Clear(); for (int j = 0; j <= leftPoker.Length - 1; j++) { list.Add(rightPoker[j]); list.Add(leftPoker[j]); } if (leftPoker.Length != rightPoker.Length) { list.Add(rightPoker[rightPoker.Length - 1]); } } else { list.Clear(); for (int j = 0; j <= leftPoker.Length - 1; j++) { list.Add(leftPoker[j]); list.Add(rightPoker[j]); } if (leftPoker.Length != rightPoker.Length) { list.Add(rightPoker[rightPoker.Length - 1]); } } } return list; }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值