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