美文网首页
53.C# Convert类型转换类

53.C# Convert类型转换类

作者: 技术老小子 | 来源:发表于2024-03-20 20:03 被阅读0次

摘要


将一个基本数据类型转换为另一个基本数据类型。

类的 Convert 静态方法主要用于支持在 .NET 中转换到基本数据类型和从基数据类型转换。 支持的基类型包括Boolean、、SByteByteUInt64Int64、UInt32Int32、UInt16Int16Single、、Double、和Decimal、DateTime StringChar 此外,该 Convert 类还包含用于支持其他类型的转换的方法。

正文


常用方法

ToBase64String 转换为其用 Base64 数字编码的等效字符串表示形式
ToBoolean 转换为等效的布尔值
ToByte 转换为等效的 8 位无符号整数
ToChar 返回指定的 Unicode 字符值
ToDateTime 将指定对象的值转换为 DateTime 对象
ToDecimal 转换为等效的十进制Decimal数
ToDouble 转换为等效的双精度浮点数。
ToInt16 转换为等效的 16 位带符号整数
ToInt32 转换为等效的 32 位带符号整数。
ToInt64 转换为等效的 64 位有符号整数。
ToSByte 转换为等效的 8 位带符号整数。
ToSingle 转换为等效的单精度浮点数。

使用Convert

double d1 = 23.15;
int i1 = Convert.ToInt32(d1);//转换为整型
bool b1 = Convert.ToBoolean(d1);//转换为bool
string s1 = Convert.ToString(d1);//转换为string
string s2 = "2022-2-3";
DateTime dt1=Convert.ToDateTime(s2);//将字符串转换为日期

Convert与Parse功能基本一样

string s = "12.34";
double d1=double.Parse(s);
//System.FormatException: 'Input string was not in a correct format.
int i2 = int.Parse(s);
int i1=Convert.ToInt32(d1);

image.png

相关文章

网友评论

      本文标题:53.C# Convert类型转换类

      本文链接:https://www.haomeiwen.com/subject/uunxtjtx.html