一般我们想到转换器是否都是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 表示显式转换 修饰同上。
到此这篇关于c#自定义转换器的实现的文章就介绍到这了,更多相关c#自定义转换器内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论