C#中使用重载运算符operator进行implicit和explicit转换

关键字

	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;
        }

        //隐式声明Note转double
        public static implicit operator double(Note x)
=> 440 * Math.Pow(2, (double)x.Value / 12);
        //显示声明int转Note
        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; // explicit conversion
            Console.WriteLine($"类型:{n.GetType().ToString()} 值:{n.Value}");
            double x = n; // implicit conversion
            Console.WriteLine($"类型:{x.GetType().ToString()} 值:{x}");
            Console.WriteLine(554.37 is Note); // False
            Console.ReadKey();
        }
    }

}


截图

在这里插入图片描述

你可能感兴趣的:(C#,c#,开发语言)