欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#使用表达式树实现对象复制的示例代码

程序员文章站 2022-03-08 17:46:27
需求背景:对象复制性能优化;同时,在对象复制时,应跳过引用类型的null值复制,值类型支持值类型向可空类型的复制using common;using system;class program{...

需求背景:对象复制性能优化;同时,在对象复制时,应跳过引用类型的null值复制,值类型支持值类型向可空类型的复制

using common;
using system;
class program
{
    static void main(string[] args)
    {
        testclassa classa = new testclassa() { propa = new testclass() { name = "cs1" }, propb = "c1", propc = 1 };
        testclassa classb = new testclassa() { propa = new testclass() { name = "cs2" }, propb = "c2", propc = 2 };
        fastcopy.copy(classa, classb, false);
        console.writeline(classb.propa?.name + ":" + classb.propb + ":" + classb.propc);
        testclassa classc = new testclassa() { propa = new testclass() { name = "cs1" } };
        testclassa classd = new testclassa() { propa = new testclass() { name = "cs2" }, propb = "c2", propc = 2 };
        fastcopy.copy(classc, classd, false);
        console.writeline(classd.propa?.name + ":" + classd.propb + ":" + classd.propc);
    }
}
public class testclassa
{
    public testclass propa { get; set; }
    public string propb { get; set; }
    public int? propc { get; set; }
}
public class testclass
{
    public string name { get; set; }
}

输出:

C#使用表达式树实现对象复制的示例代码

百万次调用耗时:270-300ms

using system;
using system.collections.concurrent;
using system.collections.generic;
using system.linq;
using system.linq.expressions;
using system.reflection;
using static system.linq.expressions.expression;
namespace common
{
    public static class fastcopy
    {
        static concurrentdictionary<string, object> copiers = new concurrentdictionary<string, object>();
        /// <summary>
        /// 复制两个对象同名属性值
        /// </summary>
        /// <typeparam name="s"></typeparam>
        /// <typeparam name="t"></typeparam>
        /// <param name="source">源对象</param>
        /// <param name="target">目标对象</param>
        /// <param name="copynull">源对象属性值为null时,是否将值复制给目标对象</param>
        public static void copy<s, t>(s source, t target, bool copynull = true)
        {
            string name = string.format("{0}_{1}_{2}", typeof(s), typeof(t), copynull);
            object targetcopier;
            if (!copiers.trygetvalue(name, out targetcopier))
            {
                action<s, t> copier = createcopier<s, t>(copynull);
                copiers.tryadd(name, copier);
                targetcopier = copier;
            }
            action<s, t> action = (action<s, t>)targetcopier;
            action(source, target);
        }
        /// <summary>
        /// 为指定的两种类型编译生成属性复制委托
        /// </summary>
        /// <typeparam name="s"></typeparam>
        /// <typeparam name="t"></typeparam>
        /// <param name="copynull">源对象属性值为null时,是否将值复制给目标对象</param>
        /// <returns></returns>
        private static action<s, t> createcopier<s, t>(bool copynull)
        {
            parameterexpression source = parameter(typeof(s));
            parameterexpression target = parameter(typeof(t));
            var sourceprops = typeof(s).getproperties(bindingflags.instance | bindingflags.public).where(p => p.canread).tolist();
            var targetprops = typeof(t).getproperties(bindingflags.instance | bindingflags.public).where(p => p.canwrite).tolist();
            // 查找可进行赋值的属性
            var copyprops = targetprops.where(tprop => sourceprops.where(sprop => sprop.name == tprop.name// 名称一致 且
            && (
            sprop.propertytype == tprop.propertytype// 属性类型一致 或
            || sprop.propertytype.isassignablefrom(tprop.propertytype) // 源属性类型 为 目标属性类型 的 子类;eg:object target = string source;   或
            || (tprop.propertytype.isvaluetype && sprop.propertytype.isvaluetype && // 属性为值类型且基础类型一致,但目标属性为可空类型 eg:int? num = int num;
            ((tprop.propertytype.generictypearguments.length > 0 ? tprop.propertytype.generictypearguments[0] : tprop.propertytype) == sprop.propertytype))
            )).count() > 0);
            list<expression> expressionlist = new list<expression>();
            foreach (var prop in copyprops)
            {
                if (prop.propertytype.isvaluetype)// 属性为值类型
                {
                    propertyinfo sprop = typeof(s).getproperty(prop.name);
                    propertyinfo tprop = typeof(t).getproperty(prop.name);
                    if (sprop.propertytype == tprop.propertytype)// 属性类型一致 eg:int num = int num;    或   int? num = int? num;
                    {
                        var assign = assign(property(target, prop.name), property(source, prop.name));
                        expressionlist.add(assign);
                    }
                    else if (sprop.propertytype.generictypearguments.length <= 0 && tprop.propertytype.generictypearguments.length > 0)// 属性类型不一致且目标属性类型为可空类型 eg:int? num = int num;
                    {
                        var convert = convert(expression.property(source, prop.name), tprop.propertytype);
                        var cvassign = assign(expression.property(target, prop.name), convert);
                        expressionlist.add(cvassign);
                    }
                }
                else// 属性为引用类型
                {
                    var assign = assign(property(target, prop.name), property(source, prop.name));// 编译生成属性赋值语句   target.{propertyname} = source.{propertyname};
                    var sourcepropisnull = equal(constant(null, prop.propertytype), property(source, prop.name));// 判断源属性值是否为null;编译生成  source.{propertyname} == null
                    var setnull = istrue(constant(copynull));// 判断是否复制null值 编译生成  copynull == true
                    var setnulltest = ifthen(setnull, assign);
                    var condition = ifthenelse(sourcepropisnull, setnulltest, assign);
                    /**
                     * 编译生成
                     * if(source.{propertyname} == null)
                     * {
                     *   if(setnull)
                     *   {
                     *     target.{propertyname} = source.{propertyname};
                     *   }
                     * }
                     * else
                     * {
                     *   target.{propertyname} = source.{propertyname};
                     * }
                     */
                    expressionlist.add(condition);
                }
            }
            var block = block(expressionlist.toarray());
            expression<action<s, t>> lambda = lambda<action<s, t>>(block, source, target);
            return lambda.compile();
        }
    }
}

如果完整复制,去掉逻辑判断,同时可通过泛型类,不在使用字典,性能还可以提升。

using system;
using system.linq;
using system.linq.expressions;
using system.reflection;
namespace common
{
    public static class fastcopy<s, t>
    {
        static action<s, t> action = createcopier();
        /// <summary>
        /// 复制两个对象同名属性值
        /// </summary>
        /// <typeparam name="s"></typeparam>
        /// <typeparam name="t"></typeparam>
        /// <param name="source">源对象</param>
        /// <param name="target">目标对象</param>
        /// <param name="copynull">源对象属性值为null时,是否将值复制给目标对象</param>
        public static void copy(s source, t target, bool copynull = true)
        {
            action(source, target);
        }
        /// <summary>
        /// 为指定的两种类型编译生成属性复制委托
        /// </summary>
        /// <typeparam name="s"></typeparam>
        /// <typeparam name="t"></typeparam>
        /// <param name="copynull">源对象属性值为null时,是否将值复制给目标对象</param>
        /// <returns></returns>
        private static action<s, t> createcopier()
        {
            parameterexpression source = expression.parameter(typeof(s));
            parameterexpression target = expression.parameter(typeof(t));
            var sourceprops = typeof(s).getproperties(bindingflags.instance | bindingflags.public).where(p => p.canread).tolist();
            var targetprops = typeof(t).getproperties(bindingflags.instance | bindingflags.public).where(p => p.canwrite).tolist();
            // 查找可进行赋值的属性
            var copyprops = targetprops.where(tprop => sourceprops.where(sprop => sprop.name == tprop.name// 名称一致 且
            && (
            sprop.propertytype == tprop.propertytype// 属性类型一致
            )).count() > 0);
            var block = expression.block(from p in copyprops select expression.assign(expression.property(target, p.name), expression.property(source, p.name)));
            expression<action<s, t>> lambda = expression.lambda<action<s, t>>(block, source, target);
            return lambda.compile();
        }
    }
}

百万次耗时:100ms左右

到此这篇关于c#使用表达式树实现对象复制的示例代码的文章就介绍到这了,更多相关c#表达式树对象复制内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!