C#的类型转换
来源:互联网 发布:2016网络在逃犯名单 编辑:程序博客网 时间:2024/05/29 02:57
使用implicit和explicit关键字可进行隐式和显式转换,具体格式如下:
public static implicit/explicit operator targetType(sourceType name)
示例代码:
using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication1{ abstract class person { protected string _name; public person(string name) { _name = name; } public string getname() { return _name; } public abstract void duty(); } class student:person { protected int _id; public student(string name,int id):base(name) { _id = id; } public int getid() { return _id; } public override void duty() { Console.WriteLine("上学"); } //隐式转换 public static implicit operator teacher(student stu) { return new teacher(stu.getname(), stu.getid()); } } class teacher : person { protected int _id; public teacher(string name, int id) : base(name) { _id = id; } public int getid() { return _id; } public override void duty() { Console.WriteLine("教学"); } //显式转换 public static explicit operator student(teacher tea) { return new student(tea.getname(), tea.getid()); } } class test { static void Main(string[] args) { student s1=new student("学生",1); teacher t1=new teacher("老师",2); teacher t = s1;//隐式转换 student s = (student)t1;//显式转换 Console.WriteLine(t.getname()); Console.WriteLine(s.getname()); Console.Write("输入任意字符结束程序"); Console.Read(); } }}
阅读全文
0 0
- C# 的类型转换
- C#的类型转换
- C#的类型转换
- C#的类型转换
- C#的类型转换
- C#类型的转换
- C#的类型转换
- C#的类型转换
- C#的强制类型转换
- C#输入的类型转换
- C# 的类型转换 -4
- C# 枚举类型的转换
- C#类型转换的方法
- C#的类型转换:显示类型转换、强制类型转换、不兼容类型转换
- C#中值类型和引用类型及类型的转换
- C# 中各种类型的相互转换
- C#中枚举类型的转换问题
- C# int类型的转换方法区别
- 堆排序 C++实现
- 算法导论 练习题 20.2-1
- maven项目驱动报错
- JSP中文乱码问题终极解决方案
- Spring的属性注入到bean实例的细节
- C#的类型转换
- ios开发 数字转汉字
- python学习笔记(一)
- 到底什么才是自动化巡检?
- Vue.js总体梳理
- 利用伪元素:before实现的快递单查询垂直列表的demo
- javscript 七牛上传图片
- 网络端口的调研
- mybatis入门