自訂隱式轉換和顯式轉換c#簡單例子,

來源:互聯網
上載者:User

自訂隱式轉換和顯式轉換c#簡單例子,

自訂隱式轉換和顯式轉換c#簡單例子 (出自朱朱家園http://blog.csdn.net/zhgl7688)

例子:對使用者user中,使用者名稱first name和last name進行轉換成合成一個限定長度為10個字元新name。

自訂隱式轉換:

namespace transduction{    public partial class transductionForm : Form    {        public transductionForm()        {            InitializeComponent();        }        private void btnDisplay_Click(object sender, EventArgs e)        {            User user = new User() { FirstName = textBox1.Text, LastName = textBox2.Text };            LimitedName limitedName = user;//將user轉換為limitedName            string lName = limitedName;//將limitedName轉換為字串型            listBox1.Items.Add(lName);        }    }    class LimitedName    {        const int MaxNameLength = 10;//名字最長為10個字元        private string _name;        public string Name        {            get { return _name; }            set { _name = value.Length < 10 ? value : value.Substring(0, 10); }        }        public static implicit operator LimitedName(User user)// public static implicit operator是必須的,名稱LimitedName為目標類型,參數User為來源資料。        {            LimitedName ln = new LimitedName();//建立目標執行個體            ln.Name = user.FirstName + user.LastName;//將來源資料賦於目標執行個體            return ln;        }        public static implicit operator string(LimitedName ln)//         {            return ln.Name;//返回目標執行個體的資料。        }    }    class User    {        public string FirstName { get; set; }        public string LastName { get; set; }    }}
自訂顯式轉換:

將上面程式中的用explicit替換implicit,

 LimitedName limitedName =(LimitedName ) user;//在user增加顯式轉換類型


此檔案由朱朱編寫,轉載請註明出自朱朱家園http://blog.csdn.net/zhgl7688

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.