作者: Jowen
查看: 8207|回复: 14
打印 上一主题 下一主题

[教程] 【C#泛型的好处】举个最简单例子说明吧

[复制链接]
楼主
xiaobo 发表于 2015-6-8 17:37:07 | 显示全部楼层
我也来玩玩,虽然与LZ不是同一个意思,不过同样是泛型的使用:
[C#] 纯文本查看 复制代码
namespace ClearTexts {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }

        public static void ClearText<T>(T t) {
            var type = t.GetType();
            if (type.GetProperty("Text") != null) {
                type.GetProperty("Text").SetValue(t, string.Empty, null);
            }
            if (type.GetProperty("Controls") != null) {
                var controls = (type.GetProperty("Controls").GetValue(t, null) as Control.ControlCollection);
                foreach (Control item in controls) {
                    ClearText(item);
                }
            }
        }

        private void button1_Click(object sender, EventArgs e) {
            ClearText(textBox3);
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) {
            ClearText(groupBox1);
        }
    }
}




沙发
xiaobo 发表于 2015-6-9 08:56:52 | 显示全部楼层
Jowen 发表于 2015-6-8 22:10
恩,用的反射,更高级点,谢谢

不客气哈~其实就是为了去掉一个参数单纯的写关于Text的玩玩
板凳
xiaobo 发表于 2015-6-9 22:13:36 | 显示全部楼层
Jowen 发表于 2015-6-9 09:36
我当时写的时候没有注意,其实可以简化的,最终版本是这样的,就一个参数[mw_shl_code=csharp,true]
/// ...

嗯,是的
您需要登录后才可以回帖 登录 | 加入CSkin博客

本版积分规则

QQ|申请友链|小黑屋|手机版|Archiver|CSkin ( 粤ICP备13070794号

Powered by Discuz! X3.2  © 2001-2013 Comsenz Inc.  Designed by ARTERY.cn
GMT+8, 2024-5-5 10:07, Processed in 0.543692 second(s), 32 queries , Gzip On.

快速回复 返回顶部 返回列表