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

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

问题描述

我有一些功能,如

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;
}

我想编写一些泛型函数,如
private static T 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!

Ilan。

推荐答案

为了利用反射,谷歌上没有可以这样做的例子。

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

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

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