一般我们想到转换器是否都是Int 转换成 double类型,Double 类型转换成Int类型。或者更复杂一点的是Object 转换成 File 等引用类型。这种都涉及到了类型之间的转换,其实C#已经帮我们实现了。
如何实现一个更复杂的;两个类型之间 的转换呢?这里需要我们自定义类型转换方法 。
1.自定义转换语法
这里列举一个例子,我们这里有Student类 和 Employ类 我想实现这两种数据类型的转换。
这里有两个方法,第一个方法将Studnet 类型转换成Employee类型。
用Static implicit 修饰 是代表隐式转换 返回的是Employee 实例就是 转换成Employee类型。
用Static explicit 修饰代码的是显示转换,返回的是Student 实例就是转换成Student类型。
2.使用
这里我把之前的单例模式再复习一遍。
namespace Study12_自定义数据类型转换.Common
{
public class Singleton<T> where T : class
{
private static object _object = new object();
private static T _instance;
public static T Instance
{
get
{
if (_instance == null)
{
lock (_object)
{
if (_instance == null)
{
_instance = Activator.CreateInstance<T>();
}
return _instance;
}
}
return _instance;
}
}
}
}
public class DataConverter:Singleton<DataConverter>
{
public Student GetStudent(Employee emp)
{
return (Student)emp;
}
public Employee GetEmployee(Student student)
{
return student;
}
}
使用
internal class Program
{
static void Main(string[] args)
{
Employee employee= DataConverter.Instance.GetEmployee(new Student
{
Id = 1,
Name = "小明"
});
employee.DoWork();
Console.WriteLine("Hello, World!");
//throw new NotImplementedException();
}
}
输出
3.总结
static implicit 表示隐式类型转换 修饰要转换的类型 返回该类型对象 没有方法名,这里的方法名就是转换的类型。
Static explicit 表示显式转换 修饰同上。