c# 用户自定义转换

  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 = new Program("a", 10);
            //将Program 对象转换为int
            int age = temp;
            Console.WriteLine(temp.Name+"'"+age);
            //把int转换为Program对象
            Program program = 11;
            Console.WriteLine(temp.Name + "'" + age);
        }
    }

 

posted @ 2018-12-09 20:19  紅人  阅读(228)  评论(0编辑  收藏  举报