类型转换是C#基础中很重要的一个知识点,特把遇到过的整理出来,供大家一起学习。
using System;
namespace lesson01{
class MainClass{
public static void Main (string[] args)
{
//常量——const
//数据类型 常量名 = 值(固定了,无法修改)注:常量不可二次赋值。
const double PAI = 3.14;
Console.WriteLine ("PAI={0}",PAI);
Console.ReadLine ();
//隐式类型转换(自动类型转换)
//原类型小于目标类型(小转大)
//byte < short < int < long
int a = 3;
float b = 4.5f;
short c = 5;
b = a;
a = c;
Console.WriteLine ("a={0},b={1}",a, b);
Console.ReadLine ();
//显式类型转换(强制类型转换)
//原类型大于目标类型(大转小)
//1、使用类型进行转换
int i = 5;
float j = 15.5f;
i= (int)j;
Console.WriteLine ("i={0}",i);
Console.ReadLine ();
//2、使用“Convert.To数据类型”进行转换
int x = 6;
float y = 9.1f;
x = Convert.ToInt32(y); //Int32—int,Int16—short,Int64—long
int r = 4;
float t= Convert.ToSingle(r); //转float时,用ToSingle
double z =Convert.ToDouble(r); //转double
Console.WriteLine ("x={0},t={1},z={2}",x,t,z);
Console.ReadLine ();
//3、使用类型的解析方法”数据类型.Parse”进行转换
string str = "123";
int v = int.Parse (str);
string s = "5.6";
float ss = float.Parse(s);
Console.WriteLine ("v={0},vv={1}",v, ss);
Console.ReadLine ();
//从浮点类型的字符串转换到int需要两步
int aa = (int)double.Parse("35.1");
int bb = (int)Convert.ToDouble("35.1");
Console.WriteLine ("aa={0},bb={1}",aa, bb);
Console.ReadLine ();
}
}
}