用戶自定義轉換(隱式implicit、顯式explicit)

除了標準轉換,我們還可以爲類和結構定義隱式(implicit)顯式(explicit)轉換。

用戶自定義轉換的約束

implicit(隱式轉換)

    class Person
    {
        public string Name;
        public int Age;
        public Person(string name,int age)
        {
            Name = name;
            Age = age;
        }
        public static implicit operator int(Person p)  //將person轉換爲int
        {
            return p.Age;
        }
        public static implicit operator Person(int i)  //將int轉換爲person
        {
            return new Person("aaa", i);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person("ppp", 21);
            int age = p;  //把Person對象轉換爲int
            Console.WriteLine(age);

            Person p2 = 100; //把int轉換爲Person對象
            Console.WriteLine("{0},{1}", p2.Age, p2.Name);

        }
    }

explicit(顯式轉換)

如果使用explicit運算符而不是implicit來定義相同的轉化,則需要使用強制轉換表達式來進行轉換。

 class Person
    {
        public string Name;
        public int Age;
        public Person(string name,int age)
        {
            Name = name;
            Age = age;
        }
        public static explicit operator int(Person p)  //將person轉換爲int
        {
            return p.Age;
        }
        public static explicit operator Person(int i)  //將int轉換爲person
        {
            return new Person("aaa", i);
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person p = new Person("ppp", 21);
            int age = (int)p;  //添加強制轉換
            Console.WriteLine(age);

            Person p2 = (Person)100; //添加強制追安環
            Console.WriteLine("{0},{1}", p2.Age, p2.Name);

        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章