如何写一个通用的函数,它接受一个数据行和填充一个对象的属性? [英] How do write a generic function that takes a datarow and fill an object's properties?

查看:179
本文介绍了如何写一个通用的函数,它接受一个数据行和填充一个对象的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像

private static UserInfo FillUserInfoFromDataRow(DataRow dr)
{

     UserInfo user = new UserInfo();

     user.UserID = (int) dr["UserID"];
     user.UserName = (int) dr["UserName"];
     user.ProjectID = (int) dr["ProjectID"];
     user.ClassID = (int) dr["ClassID"];
     ..............

     return user;
}



我想这样写
私有静态一些通用的功能ŧFillEntityInfoFromDataRow(DataRow的DR),这将把类似的类型ProjectInfo,JobInfo等。

I'd like to write some generic function like private static T FillEntityInfoFromDataRow(DataRow dr), that will treat analogous types ProjectInfo, JobInfo, etc.

我可以得到所有列的DataRow参数的名字,但我不知道如何让普通的T类以及如何做适当的铸件所有相应的字段。
是它的一些方法来做好这项工作?
谢谢!

I can get all columns names of the DataRow parameter, but I don't know how to get all the appropriate fields of the generic T type and how to do appropriate casting. Is it some way to do this job? Thanks!

宜兰。

推荐答案

它更好利用反射有没有例子avaible对谷歌这样做这一点。

Its better to make use of reflection there are no of example avaible on google to do this this.

检查下面的例子

namespace MyNamespace.Data
{
    class Converter
    {
        public static void Fill(object LogicObject, DataRow Row)
        {
            Dictionary<string, PropertyInfo> props = new Dictionary<string,PropertyInfo>();
            foreach (PropertyInfo p in LogicObject.GetType().GetProperties())
                props.Add(p.Name, p);
            foreach (DataColumn col in Row.Table.Columns)
            {
                string name = col.ColumnName;
                if (Row[name] != DBNull.Value && props.ContainsKey(name))
                {
                    object item = Row[name];
                    PropertyInfo p = props[name];
                    if (p.PropertyType != col.DataType)
                        item = Convert.ChangeType(item, p.PropertyType);
                    p.SetValue(LogicObject, item, null);
                }
            }

        }
    }
}

检查完整的博客文章: http://kasey-jo.blogspot.com/2009/04/using-reflection-to-fill-business-layer.html

Check the full blog post : http://kasey-jo.blogspot.com/2009/04/using-reflection-to-fill-business-layer.html

这篇关于如何写一个通用的函数,它接受一个数据行和填充一个对象的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆