当前位置: 代码迷 >> C# >> 自定义隐式转换跟显式转换c#简单例子
  详细解决方案

自定义隐式转换跟显式转换c#简单例子

热度:422   发布时间:2016-05-05 05:28:54.0
自定义隐式转换和显式转换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

  相关解决方案