C#类型转换
string str1 = Console.ReadLine();
string str2 = Console.ReadLine();
int x = Convert.ToInt32(str1);
int y = Convert.ToInt32(str2);
int result = x + y;
Console.WriteLine(result);
Console.ReadKey();
隐式类型转换(implicit)
- 不丢失精度的转换
int x = int.MaxValue;
long y = x;
文章图片
不丢失精度的隐式类型转换
- 子类向父类的转换
using System;
namespace Test
{
class User
{
public void Login()
{
Console.Write("user login\n");
}
}
class Member : User
{
public void Profile()
{
Console.WriteLine("member profile\n");
}
}
class GuildMember : Member
{
public void JoinGuild()
{
Console.WriteLine("guild member join\n");
}
}
class Program
{
static void Main(string[] args)
{GuildMember gm = new GuildMember();
Member m = gm;
User u = m;
u.Login();
m.Login();
m.Profile();
gm.Login();
gm.Profile();
gm.JoinGuild();
Console.ReadKey();
}
}
}
- 装箱(boxing)
- 可能丢失精度,甚至发生错误,即cast。
ushort maxval = ushort.MaxValue;
uint x = 65536;
ushort y = (ushort)x;
//0
文章图片
显示类型转换
- 拆箱(unboxing)
- 建议使用Convert工具类
- ToString()与数据类型的Parse/TryParse方法
Parse只能解析格式正确的数据
using System;
namespace Test
{
class User
{
public int age;
public static explicit operator Member(User user)
{
Member member = new Member();
member.age = user.age;
return member;
}
}
class Member
{
public int age = 1000;
}
class Program
{
static void Main(string[] args)
{
User u = new User();
Member m = (Member)u;
Console.WriteLine(m.age);
Console.ReadKey();
}
}
}
推荐阅读
- 一起来学习C语言的字符串转换函数
- 视频转换器哪种好用()
- 以太坊中的计量单位及相互转换
- jvm关于String
- LeetCode(03)Longest|LeetCode(03)Longest Substring Without Repeating Characters
- mysql|InnoDB数据页结构
- 接口|axios接口报错-参数类型错误解决
- 怎么将桌面上的CAD图纸添加到软件中进行BMP格式转换()
- 带你了解类型系统以及flow和typescript的基本使用
- 史前艺术的审美类型「清央美术」