基本类型
整数类型——8种
主要使用int , long 两种
类型 | 大小 | 范围 |
---|---|---|
int | 32bit | -2^32/2 ~ 2^32/ 2 |
long | 64bit | -2^64/2 ~ 2^64/2 |
浮点类型——2种
float(有效位7位) , double 主要用 double, double 有效位 15~16位
using System;
namespace basicPractice
{
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("Hello World!");//使用了Using System;所以Console前面不用加System.
double num = 1234.1234123412341234;
Console.WriteLine(num);//由于double类型的有效位数是15~16位,输出只能到1234.12341234123,共15位。
double a = 2E2;//nEn表示n乘以10的n次方,所以2E2=2X10^2=200
Console.WriteLine(a);
}
}
}
浮点类型——金融计算
decimal 128bit 有效位28~29 金融计算专用
字面值
整数——int
浮点数——double
指数写法——nEn 表示 n*10^n
十六进制写法——Ox开头
bool false true
char
\n 换行
\t 制表符 经常用于对齐
\ 转义
\a 发出声音
string
在字符串前面加上@可以取消转义
string str2 = @"ftp:\hhhh\uuuu\1.txt";
string str3 = "ftp:\\hhhh\\uuuu\\1.txt";//str2 跟str3输出是一样的
Console.WriteLine("@取消转义" + str2 + "\n" + str3);
StringBuild
对字符串进行修改操作时,StringBuild效率高于string。
可用计时器做个对比。
计时器的使用:
using System;
using System.Diagnostics;//使用计时器
namespace basicPractice
{
class Program
{
static void Main(string[] args)
{
//使用秒表stopwatch作为计时器,计时器可以用中文命名
Stopwatch 计时器 = new Stopwatch();
计时器.Start();//计时器开始
计时器.Stop();//计时器结束
Console.WriteLine(计时器.ElapsedMilliseconds);//输出时间
}
}
}
string 和 StringBuild 用时对比:
using System;
using System.Diagnostics;//使用计时器
using System.Text;
namespace basicPractice
{
class Program
{
static void Main(string[] args)
{
//使用秒表stopwatch作为计时器,计时器可以用中文命名
Stopwatch 计时器 = new Stopwatch();
计时器.Start();//计时器开始
string str1 = string.Empty;
for(int i = 0; i < 100000; i++)
{
str1 += i.ToString();
}
计时器.Stop();//计时器结束
Console.WriteLine("string用时:" + 计时器.ElapsedMilliseconds);//输出时间
计时器 = new Stopwatch();
计时器.Start();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 100000; i++)
{
sb.Append(i.ToString());
}
计时器.Stop();
Console.WriteLine("StringBuild用时:" + 计时器.ElapsedMilliseconds);
}
}
}
输出:
string用时:10220
StringBuild用时:4
类型分类
1、值类型:所有基本类型
2、引用类型:string等
3、null只能用户引用类型,表示没有引用任何对象;
4、string.empty等价于 “”,不等价于null;
5、可空修饰:int?专用于数据库中int类型值为null的情况;
6、隐式类型:var 值的类型是确定的的时候,可以var代替。
类型转换
1、显式转换 ——由高到低,checked 用于检查值范围是否溢出
int a;
checked
{
a = int.MaxValue;
a = a + 1;
}
Console.WriteLine(a);
2、隐式转换——由低到高,自动转换
3、转换函数
.Parse()
.TryParse()
.toString
var str1 = Console.ReadLine();
var str2 = Console.ReadLine();
//Console.WriteLine(str1 + str2);//此时是字符串相连
//int a = int.Parse(str1);//利用.Parse()将字符串转换为int,double.Parse(str)也是一样的用法
//int b = int.Parse(str2);
//Console.WriteLine(a + b);//此时输出数字相加
/// 当输入的字符串不是数字时,以上的.Parse()转换会出现问题。需要用到tryParse()
int c, d;
if(int.TryParse(str1, out c) && int.TryParse(str2, out d)){
Console.WriteLine(c + d);
}
else {
Console.WriteLine("解析错误!");
}