zoukankan      html  css  js  c++  java
  • 自己定义隐式转换和显式转换c#简单样例

    自己定义隐式转换和显式转换c#简单样例 (出自朱朱家园http://blog.csdn.net/zhgl7688

    样例:对用户user中,usernamefirst 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

  • 相关阅读:
    能ping通Linux但是ssh连不上问题解决方法
    php遍历目录与文件夹的多种方法详解
    Apache与Nginx的优缺点比较
    Apache查看连接数和限制当前的连接数
    【MySql】性能优化之分析命令
    PHP实现各种经典算法
    301、404、200、304等HTTP状态
    常用服务器资源地址集合
    关于WAMP的apache 人多了就访问非常卡的问题解决方法
    HTML基础
  • 原文地址:https://www.cnblogs.com/jzssuanfa/p/6900389.html
Copyright © 2011-2022 走看看