Simple examples of custom implicit conversions and explicit conversions in C # (from Zhu Zhu Homeland http://blog.csdn.net/zhgl7688)
Example: The user name First name and last name are converted to a composite with a qualified length of 10 characters descriptors name.
Custom Implicit conversions:
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;//Converts the user to Limitedname string lName = limitedname;//converts limitedname to string type LISTBOX1.ITEMS.ADD (LName); }} class Limitedname {const int maxnamelength = 10;//The longest 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, name Limitedna The Me is the target type and the parameter user is the source data. {Limitedname ln = new Limitedname ();//Establish target instance ln. Name = user. FirstName + uSer. lastname;//assigns the source data to the target instance return ln; public static implicit operator string (limitedname ln)//{return ln. name;//returns the data for the target instance. }} class User {public string FirstName {get; set;} public string LastName {get; set;} }}
To customize an explicit conversion:
Replace the implicit with explicit in the above program,
Limitedname limitedname = (limitedname) user;//Add an explicit conversion type to user
This document was written by Zhu Zhu, reproduced please indicate from Zhu Zhu Homeland http://blog.csdn.net/zhgl7688
Simple examples of custom implicit conversions and explicit conversions in C #