使用PropertyInfo类反射获取类 的类型

使用PropertyInfo类反射获取类 的类型

 

首先构造一个泛型类

public class ClassName<T>

{

}

然后定义一个方法 方法返回集合

view plaincopy to clipboardprint?
public class Class1<T> 

    public IList<T> GetData(SqlDataReader reader) 
    { 
        IList<T> list = new List<T>(); 
        Type type = typeof(T); 
        PropertyInfo[] properties = type.GetProperties(); 
 
        while (reader.Read()) 
        { 
            T t = Activator.CreateInstance<T>(); 
            for (int i = 0; i < properties.Length; i++) 
            { 
                properties[i].SetValue(t, reader[i + 1], null); 
 
            } 
 
            list.Add(t); 
        } 
 
        return list; 
    } 

    public class Class1<T>
    {
        public IList<T> GetData(SqlDataReader reader)
        {
            IList<T> list = new List<T>();
            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties();

            while (reader.Read())
            {
                T t = Activator.CreateInstance<T>();
                for (int i = 0; i < properties.Length; i++)
                {
                    properties[i].SetValue(t, reader[i + 1], null);

                }

                list.Add(t);
            }

            return list;
        }
    }

上面给出了核心代码 如果你要传递sql语句

那你的业务逻辑层 就要这一个方法也就够了!

 下面一个扩展方法 由 论坛的sql1234提供 在一次感叹 linq语法的简洁

view plaincopy to clipboardprint?
public static IEnumerable<T> GetObjects<T>(this DbDataReader rd) where T : new() 

    var fs = (from fd in typeof(T).GetFields() 
                let desc = new { field = fd, index = rd.GetOrdinal(fd.Name) } 
                where desc.index >= 0 
                select desc) 
            .ToList(); 
    foreach (var x in rd) 
    { 
        var obj = new T(); 
        fs.ForEach(d => { d.field.SetValue(obj, rd[d.index]); }); 
        yield return obj; 
    } 

public static IEnumerable<T> GetObjects<T>(this DbDataReader rd) where T : new()
{
    var fs = (from fd in typeof(T).GetFields()
                let desc = new { field = fd, index = rd.GetOrdinal(fd.Name) }
                where desc.index >= 0
                select desc)
            .ToList();
    foreach (var x in rd)
    {
        var obj = new T();
        fs.ForEach(d => { d.field.SetValue(obj, rd[d.index]); });
        yield return obj;
    }
}

 

这里,我们通过扩展方法,为任意DbDataReader都增加了一个GetObjects方法,返回任意指定类型的强类型的对象集合。
如果包括private的field才更完整。应该将 GetFields() 修改为
GetFields(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.NonPublic)

posted @ 2011-04-01 17:54  Marksion  阅读(4716)  评论(0编辑  收藏  举报