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);

相关推荐
Artech1 小时前
[MAF预定义的AIContextProvider-03]ChatHistoryMemoryProvider——赋予Agent从经验中学习的能力
ai·c#·agent·memory·maf
Scout-leaf2 天前
C#摸鱼实录——IoC与DI案例详解
c#
咕白m6252 天前
使用 C# 在 Excel 中应用多种字体样式
后端·c#
Artech2 天前
[MAF预定义的AIContextProvider-02]AgentSkillsProvider——将Agent Skills引入MAF
ai·c#·agent·agent skills·maf
LDR0063 天前
Type-C 快充全面升级!LDR6601 赋能个人护理便携电机,重塑剃须刀 / 理发器新体验
c语言·开发语言
雪碧聊技术3 天前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript
码云数智-园园3 天前
C++20 Modules 模块详解
java·开发语言·spring
swordbob3 天前
NIO的channel中什么是 fd(File Descriptor,文件描述符)
java·开发语言·nio
源分享3 天前
Java线程同步的多种实现方法(非常详细)
java·开发语言·jvm
Luminous.3 天前
C语言--day30
c语言·开发语言