关键字
operator:重载运算符关键字,设定用户自定义运算
implicit:隐式转换
explicit:显示转换
转换写法:
public static implicit/explicit operator 目标类型(源类型 参数)=> return value;
代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Test
{
public class Note
{
private int value;
public int Value { get => value; set => this.value = value; }
public Note(int x)
{
this.Value = x;
}
public static implicit operator double(Note x)
=> 440 * Math.Pow(2, (double)x.Value / 12);
public static explicit operator Note(double x)
=> new Note((int)(0.5 + 12 * (Math.Log(x / 440) / Math.Log(2))));
}
class Program
{
static void Main(string[] args)
{
Note n = (Note)554.37;
Console.WriteLine($"类型:{n.GetType().ToString()} 值:{n.Value}");
double x = n;
Console.WriteLine($"类型:{x.GetType().ToString()} 值:{x}");
Console.WriteLine(554.37 is Note);
Console.ReadKey();
}
}
}
截图
![在这里插入图片描述](https://img-blog.csdnimg.cn/26e34f01fe2a4be0a486fee2731a0136.png)