Custom implicit conversion and explicit conversion c # simple example,

Source: Internet
Author: User

Custom implicit conversion and explicit conversion c # simple example,

Custom implicit conversion and explicit conversion c # simple example (from Zhu zhujiayuan http://blog.csdn.net/zhgl7688)

For example, in user, first name and last name are converted into a new name with a limited length of 10 characters.

Custom implicit conversion:

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; // convert user to limitedName string lName = limitedName; // convert limitedName to string type listBox1.Items. add (lName) ;}} clas S LimitedName {const int MaxNameLength = 10; // The maximum name is 10 characters 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 is required. The name LimitedName is of the target type and the parameter User is the source data. {LimitedName ln = new LimitedName (); // create the target instance ln. name = user. firstName + user. lastName; // assign the source data to the return ln of the target instance;} public static implicit operator string (LimitedName ln) // {return ln. name; // return the data of the target instance.} Class User {public string FirstName {get; set;} public string LastName {get; set ;}}}
Custom explicit conversion:

Replace implicit with explicit in the above program,

LimitedName limitedName = (LimitedName) user; // Add an explicit conversion type to the user.


This document was prepared by Zhu, reproduced please indicate from Zhu jiayuan http://blog.csdn.net/zhgl7688

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.