一、介绍
implicit用于隐式转换用户定义类型,explicit显示转换用户定义类型。
- explicit 关键字用于声明必须使用强制转换来调用的用户定义的类型转换运算符。
- implicit 关键字用于声明隐式的用户定义类型转换运算符。 如果可以确保转换过程不会造成数据丢失,则可使用该关键字在用户定义类型和其他类型之间进行隐式转换。
上代码
创建实体Student
public class Student
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public DateTime CreateTime { get; set; }
}
public class StudentDto
{
public string Name { get; set; }
public int Age { get; set; }
public string CreateTime { get; set; }
}
假设有需求将实体Student 转换成 StudentDto实体,可以看到StudentDto实体跟Student属性相比,少了Id属性及CreateTime类型不同,哪我们初次遇到此情况会怎么做,可能会单独写个装换方法如下:
public StudentDto Convert(Student stu)
{
return new StudentDto
{
Name = stu.Name,
Age = stu.Age,
CreateTime = stu.CreateTime.ToShortDateString()
};
}
其实c#提供一个较方便的功能,请看代码
二、implicit
public class StudentDto
{
public string Name { get; set; }
public int Age { get; set; }
public string CreateTime { get; set; }
/// <summary>
/// 可以隐式将 Student 类型转为 StudentDto 类型
/// </summary>
/// <param name="stu"></param>
public static implicit operator StudentDto(Student stu)
{
return new StudentDto
{
Name = stu.Name,
Age = stu.Age,
CreateTime = stu.CreateTime.ToShortDateString()
};
}
}
使用: 可以看到直接就可以将Stuent类型 赋值个StudentDto
static void Main(string[] args)
{
Student stu = new Student();
stu.Age = 25;
stu.CreateTime = DateTime.Now;
stu.Id = 1;
stu.Name = "乔武林";
StudentDto stuDto = stu;
Console.WriteLine(stuDto.Name);
Console.Read();
}
三、explicit
public class StudentDto
{
public string Name { get; set; }
public int Age { get; set; }
public string CreateTime { get; set; }
/// <summary>
/// 可以显示将 Student 类型转为 StudentDto 类型
/// </summary>
/// <param name="stu"></param>
public static explicit operator StudentDto(Student stu)
{
return new StudentDto
{
Name = stu.Name,
Age = stu.Age,
CreateTime = stu.CreateTime.ToShortDateString()
};
}
}
使用:Student想要装换StudentDto类型需要 强制类型 装换
static void Main(string[] args)
{
Student stu = new Student();
stu.Age = 25;
stu.CreateTime = DateTime.Now;
stu.Id = 1;
stu.Name = "乔武林";
StudentDto stuDto = (StudentDto)stu;
Console.WriteLine(stuDto.Name);
Console.Read();
}
四、补充
个人感觉现在这种方式很少有人用了吧,如果类型转换不太频繁该方式也能满足需要,可是在项目中需频繁大量进行实体类型转换,可以使用Mapster或AutoMapper。