该引用摘自:explicit(C# 参考)
该引用摘自:使用转换运算符(C# 编程指南)
仍以Student为例,取语文和数学成绩的和,不使用explicit
class Student
{
/// <summary>
/// 语文成绩
/// </summary>
public double Chinese { get; set; }
/// <summary>
/// 数学成绩
/// </summary>
public double Math { get; set; }
}
求和:
class Program
{
static void Main(string[] args)
{
var a = new Student
{
Chinese = 90.5d,
Math = 88.5d
};
//a的总成绩 语文和数据的总分数
Console.WriteLine(a.Chinese + a.Math);
}
}
使用explicit
class Student
{
/// <summary>
/// 语文成绩
/// </summary>
public double Chinese { get; set; }
/// <summary>
/// 数学成绩
/// </summary>
public double Math { get; set; }
public static explicit operator double(Student a)
{
return a.Chinese + a.Math;
}
}
求和:
class Program
{
static void Main(string[] args)
{
var a = new Student
{
Chinese = 90.5d,
Math = 88.5d
};
//a的总成绩 语文和数据的总分数
Console.WriteLine((double)a);
}
}