自定义隐式转换 public static implicit operator 和显式转换

来源:互联网 发布:微信h5软件 编辑:程序博客网 时间:2024/06/06 05:34

例子:对用户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增加显式转换类型



0 0
原创粉丝点击