自訂資料類型轉換Demo

來源:互聯網
上載者:User

    對於基底類型之間的資料類型轉換或者特定對象之間類型轉換,目前的編譯器都可以幫我們完成。

    但是有時候,我們需要在兩個非基底類型,他們之間也沒有繼承關係的對象之間進行類型轉換,比如類與int之間的轉換;這個時候,只能由我們自己定義。

    

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace Demo1
  5. {
  6.     class Demo2
  7.     {
  8.         static void Main()
  9.         {
  10.             myAge a = 25;
  11.             a.show();
  12.             myAge myage = new myAge(40);
  13.             Console.WriteLine((Int32)myage);
  14.         }
  15.     }
  16.     class myAge
  17.     {
  18.         private int age;
  19.         public int Age
  20.         {
  21.             get { return age; }
  22.             set { age = value; }
  23.         }
  24.         public myAge(int age)
  25.         {
  26.             this.age = age;
  27.         }
  28.         public void show()
  29.         {
  30.             Console.WriteLine(age);
  31.         }
  32.         public static implicit operator myAge(int num)
  33.         {
  34.             return new myAge(num);
  35.         }
  36.         public static explicit operator Int32(myAge age)
  37.         {
  38.             return age.age;
  39.         }
  40.     }
  41. }

    注意:

    1.和運算子多載一樣,這裡的定義也必須Public, static

    2.傳回值或者參數必須是所在對象的類型

    3.可以隱式可以顯式轉換

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.