首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > asp.net >

SetValue映射属性赋值的有关问题

2013-07-11 
SetValue映射属性赋值的问题本帖最后由 will_stier 于 2013-07-07 00:29:09 编辑public static T CopyToT

SetValue映射属性赋值的问题
本帖最后由 will_stier 于 2013-07-07 00:29:09 编辑


        public static T CopyToT<S>(S source) where S:new()
        {
            T result = new T();
            Type type = typeof(T);
            PropertyInfo[] properties =  type.GetProperties();
            PropertyInfo[] sProperties = typeof(S).GetProperties();

            foreach (var item in properties)
            {
                try                    
                {
                    //if source has this Property
                    bool flag = false;

                    foreach (var q in sProperties)
                    {
                        if (q.ToString() == item.ToString())
                        {
                            flag = true;
                        }
                    }

                    if (flag)
                    {


                        //set value for this Property
                        item.SetValue(result,item.GetValue(source,null),null);
                    }
                }
                catch
                {
                    continue;
                }
                
            }
            return result;
        }


可以正确的执行到26行,但是26行执行的时候总是出现异常(类型不一致)

该方法试图用来将存储过程查询到的Student表中的记录(匿名类型)赋值给一个Student实体类。

参数T是Student,S是查询到的匿名类型

我调用的时候如下:

         public static List<Student> GetStudentsByClassName(string className)
        {
            SPMEntities db = new SPMEntities();
            var query = db.GetStudentByClassName(className);

            List<Student> list = new List<Student>();
            foreach (var item in query)
            {
                //copy item value to a student object;
                list.Add(ConvertHelper<Student>.CopyToT(item));   
            }
            return list;
        }




请问public static T CopyToT<S>(S source) where S:new()方法如何修改? 类 异常 映射
[解决办法]
set之前行判断一下当前属性的类型。。然后再把后面的值强转一下就可以啊。。我以前是这样实现的。。。
[解决办法]
该回复于2013-07-07 11:34:56被管理员删除

热点排行