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;

C#类型转换
文章图片
不丢失精度的隐式类型转换
  • 子类向父类的转换
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)
显示类型转换(explicit)
  • 可能丢失精度,甚至发生错误,即cast。
ushort maxval = ushort.MaxValue; uint x = 65536; ushort y = (ushort)x; //0

C#类型转换
文章图片
显示类型转换
  • 拆箱(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(); } } }

    推荐阅读