explicit 和 implicit 属于转换运算符,如用这两者可以让我们自定义的类型支持相互交换
explicti 表示显式转换,如从 A -> B 必须进行强制类型转换(B = (B)A)
implicit 表示隐式转换,如从 B -> A 只需直接赋值(A = B)
隐式转换可以让我们的代码看上去更漂亮、更简洁易懂,所以最好多使用 implicit 运算符。不过!如果对象本身在转换时会损失一些信息(如精度),那么我们只能使用 explicit 运算符,以便在编译期就能警告客户调用端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace implicit_explicit
{
class Program
{
static void Main(string[] args)
{
TesImplicit t = new TesImplicit();
User u = new User() { Id = 1, Name = "lichaoqiang" };
Console.WriteLine("隐式转换-----------------------------------------------------------------");
Customer c = u;
Console.WriteLine(c.CustomerId+"="+c.CustomerName);
#region 2>显示转换
Customer customer = u;
VIP v = (VIP)customer;
Console.WriteLine("显示转换-----------------------------------------------------------------");
t.GetVIPInfo(v);
#endregion
Console.ReadLine();
}
}
/// <summary>
/// test case
/// </summary>
public class TesImplicit
{
/// <summary>
/// get the customer infomation
/// </summary>
/// <param name="customer"></param>
public void GetCusterInfo(Customer customer)
{
Console.WriteLine("Customer:" + customer.CustomerName);
}
public void GetVIPInfo(VIP vip)
{
Console.WriteLine("VIP:" + vip.VName);
}
}
/// <summary>
///
/// </summary>
public class User
{
/// <summary>
///
/// </summary>
public long Id { get; set; }
/// <summary>
///
/// </summary>
public string Name { get; set; }
/// <summary>
/// 隐式转换
/// </summary>
/// <param name="u"></param>
/// <returns></returns>
public static implicit operator Customer(User u)
{
return new Customer()
{
CustomerId = u.Id,
CustomerName = u.Name
};
}
}
/// <summary>
///
/// </summary>
public class Customer
{
/// <summary>
///
/// </summary>
public long CustomerId { get; set; }
/// <summary>
///
/// </summary>
public string CustomerName { get; set; }
/// <summary>
/// 显示转换
/// </summary>
/// <param name="c"></param>
/// <returns></returns>
public static explicit operator VIP(Customer c)
{
return new VIP()
{
VID = c.CustomerId,
VName = c.CustomerName
};
}
}
/// <summary>
///
/// </summary>
public class VIP
{
/// <summary>
///
/// </summary>
public long VID { get; set; }
/// <summary>
///
/// </summary>
public string VName { get; set; }
}
}