C#——类型转换

Convert:

Convert是一个类,类中包含,ToInt32(),ToDouble(),ToString()等函数。

Console同样是一个类,包含WriteLine(),ReadKey(),ReadLine()。

string str = Console.ReadLine();

int t = Convert.ToInt32(str);//字符串带小数点不能直接转为Int类型

//实质是调用"int.Parse()"函数; //int number=int.Parse(str);转换成功赋值给number,否则抛异常

Console.WriteLine(t);

double r = Convert.ToDouble(str);

Console.WriteLine("{0:0.000}",r);//保留三位小数

**int.TryParse(str,out number)**同样将字符转换为int类型.固定格式(字符串,out int类型的变量) //逗号不能丢

string str = Console.ReadLine();

int number=0;

bool b = int.TryParse(str, out number);//str待转换的字符串,number是int类型

Console.WriteLine(b);//转换成功则为True否则False

Console.WriteLine(number);转换成功,值被赋给number,否则输出0(和number的初始值无关)

所有类型都能转换为string类型,调用ToString()

// int b = 1;

//double b = 3.14;

//decimal b=3.14m ;

Gender b = Gender.男;//Gender声明的一个枚举类型的变量;

string str = b.ToString();

Console.WriteLine(str);

相关推荐
SomeOtherTime14 小时前
Rust所有权(AI回答)
开发语言·后端·rust
Easyhood14 小时前
Android 开发入门实践(十四):Compose 副作用入门与四个常用 API
android·开发语言·kotlin·android jetpack·compose
白杨尚青15 小时前
C++进阶篇(六):map 和 set 的模拟实现——用红黑树封装 mymap/myset(迭代器 + operator[])
开发语言·c++·迭代器·stl·set·map·红黑树
饮水桶_T19 小时前
JAVA IO流笔记
开发语言·数据结构·算法
Felven21 小时前
C. Brr Brrr Patapim
c语言·开发语言
路溪非溪1 天前
python标准库使用总结
开发语言·python
SomeOtherTime1 天前
Rust 面向对象介绍(AI回答)
开发语言·python·rust
zh_xuan1 天前
kotlin常见面试题
开发语言·kotlin·面试题
草莓熊Lotso1 天前
【C++ 基于微服务的即时通讯系统】文件存储子服务实战:UUID生成、文件IO封装与全接口单元测试
开发语言·网络·数据库·c++·微服务·架构·单元测试
huaqianzkh1 天前
WinForm C#:循环修改控件UI闪烁卡顿?SuspendLayout / ResumeLayout 与 BeginUpdate 优化
开发语言·ui·c#