c# 用户自定义转换

时间:2023-03-08 17:54:28
  class Program
    {
        public string Name;
        public int Age;

        public Program(string name ,int age)
        {
            Name = name;
            Age = age;
        }

        public static implicit operator int(Program p)//将person 转换为int
        {
            return p.Age;
        }

        public static implicit operator Program(int i)//将int转换为person
        {
            return new Program("n", i);
        }

        static void Main(string[] args)
        {

            Program temp = );
            //将Program 对象转换为int
            int age = temp;
            Console.WriteLine(temp.Name+"'"+age);
            //把int转换为Program对象
            Program program = ;
            Console.WriteLine(temp.Name + "'" + age);
        }
    }