佛山软件定制

编写代码生成器自动赋值方法

在使用代码生成器的时候,会成生很多不必要的代码.

假设如下环境,自动生成一个查询数据表的存储过程和表的类,使用SqlHelper返回结果

 

那么在返回表类型的时候一个一个属性的赋值是很麻烦的,这里我们使用反射自动赋值!

如果在存储过程中参数和表列不匹配的将自动调过!

 

强烈推荐,非常好用!调用如下代码:

/* written by newmin atnet.cc */
public static AClass getaccount(string username)
        {
            AClass a = new AClass();                              //创建表的实例
            OneProdure p = new OneProdureA();             //创建存储过程实例
            p.ExecuteNonQuery();                                  //执行查询,从数据库返回数据赋值给p

            DataHelper.CloneObjectData<OneProdure, AClass>(p, a);

            return a;
}

东方网新,为您提供专业的网站建设,软件开发,网络营销SEO,网络推广服务,代理国外主机空间,域名注册,服务热线:(+86)18608275575,电子邮件:master#atnet.cc;欢迎您访问东方网新网站:www.atnet.cc

DataHelper.CloneObjectData<T,T>的定义如下:

/*
 * Author   :   Newmin  www.atnet.cc
 * Date     :   2010/10/27 14:33
 */
namespace Atnet.Data
{
    using System;
    using System.Reflection;
    using System.Collections.Generic;
    using System.Text;

    /// <summary>
    /// 数据辅助类
    /// </summary>
    public static class DataHelper
    {
        /// <summary>
        /// 拷贝对象的数据
        /// </summary>
        /// <param name="s">包含数据的对象</param>
        /// <param name="c">要拷贝数据的对象</param>
        public static void CloneObjectData<SourceType, CloneType>(SourceType s, CloneType c) where SourceType : class
        {
            //获取各自的属性
          PropertyInfo[] props = typeof(SourceType).GetProperties();
            PropertyInfo[] cp = typeof(CloneType).GetProperties();

            PropertyInfo _p;
            foreach (PropertyInfo p in props)
            {
                _p = Array.Find(cp, a => string.compare(a.name,p.name,true)==0);
                if (_p != null) _p.SetValue(c, p.GetValue(s, null), null);
            }
        }
    }
}

 

虽然代码生成器可以减少代码编写量,加上上述的方法更是如此,但还是建议不要使用代码生成器!

 

 转自:http://blog.atnet.cc/dotnet/code-tool-custom-clone-data/

 

 

 

posted on 2010-10-27 16:14  New.min  阅读(523)  评论(0编辑  收藏  举报

导航