首页 新闻 会员 周边

c# 泛型问题。。

0
悬赏园豆:10 [已关闭问题] 关闭于 2013-04-14 12:42

各位大神在项目开发中使用泛型的多吗?有没有比较经典的应用???

 

可否贴出来看看。。

KeVinDurant的主页 KeVinDurant | 初学一级 | 园豆:5
提问于:2013-03-27 23:23
< >
分享
所有回答(8)
0

在mvc模式中,常常出现Enumerable<model>

滴答的雨 | 园豆:3660 (老鸟四级) | 2013-03-27 23:42

贴代码...说明下吧。。

支持(0) 反对(0) KeVinDurant | 园豆:5 (初学一级) | 2013-03-27 23:52
0

泛型+反射很好用。用处也不少,关键在于个人喜好。还有你要粘贴代码,那种程度的。是想了解泛型用途还是了解怎样使用泛型?

伏草惟存 | 园豆:1420 (小虾三级) | 2013-03-28 07:45
0

多,现在的 集合 一般用到泛型

Qlin | 园豆:2403 (老鸟四级) | 2013-03-28 08:59
0

Repository模式一般可以使用泛型接口配合泛型类来实现,.net中的集合IEnumerable及它大部分子类都是实现了泛型的,对于泛型与object类型的对比,泛型在性能上要远远优于object。

interface IRepository<T> where T:class{

void Insert(T entity);

}

class Repository<T>:IRepository<T> where T:class{

public void Insert(T entity){

throw new NotImplement("...");

}

}

张占岭 | 园豆:464 (菜鸟二级) | 2013-03-28 09:04
0

173844862 .Net 高级交流部落

辛巴 | 园豆:622 (小虾三级) | 2013-03-28 09:14
0

list<>这个用的最多了

chenping2008 | 园豆:9836 (大侠五级) | 2013-03-28 09:25

是啊。简单来说泛型解决了装箱拆箱的问题。List<T>和Dictionary<T1,T2>用的最多。

支持(0) 反对(0) Luke Zhang | 园豆:293 (菜鸟二级) | 2013-03-28 13:25
0

这个使用很多,我们经常用的就包括读取数据,有时从数据库读取的内容为DataTable,然后利用泛型+返回,动态转换为List<>这种

/// <summary>
    /// 实体转换辅助类
    /// </summary>
    public class ModelConvertHelper<T> where  T : new()
    {
        public static IList<T> ConvertToModel(DataTable dt)
        {
            // 定义集合
            IList<T> ts = new List<T>();

            string tempName = "";

            // 获得此模型的公共属性
            PropertyInfo[] propertys =typeof(T).GetProperties();

            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
              
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;

                    // 检查DataTable是否包含此列
                    if (dt.Columns.Contains(tempName))
                    {
                        // 判断此属性是否有Setter
                        if (!pi.CanWrite) continue;

                        object value = dr[tempName];
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }

                ts.Add(t);
            }

            return ts;

        }
    }
Fencer | 园豆:7 (初学一级) | 2013-03-28 11:05
0
///项目信息
        private void InitDate()
        {
            list = new List<ProjectStat>();
            int id = 0;
            for (int i = 0; i < 4; i++)
            {
                list.Add(new ProjectStat(id, "成品油管道工程", "201212", 500128.2, 531, "电力", 1)); id++;
                list.Add(new ProjectStat(id, "济适用房建设工程", "201210013", 500128.2, 531, "房地", 2)); id++;
                list.Add(new ProjectStat(id, "水土保持工程", "201212040015", 500128.2, 231, "水利", 1)); id++;
            }
        }
夏小米_ | 园豆:220 (菜鸟二级) | 2013-03-28 15:40

这样我就实现 了List里面存N多类型数据,取出来想怎么用怎么用的特点,泛型是一个非常实用的思想

支持(0) 反对(0) 夏小米_ | 园豆:220 (菜鸟二级) | 2013-03-28 15:43
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册