使用C#将属性值复制到另一个对象 [英] Copy the property values to another object with C#

查看:811
本文介绍了使用C#将属性值复制到另一个对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要将属性值从一个对象复制到另一个对象,我们通常使用以下语法实现:

To copy the property values from one object to another, we usually achieve with following syntax:

ca.pro1 = cb.pro2;
ca.pro2 = cb.pro2;

其中ca和cb属于同一类。

where ca and cb are of the same class.

有没有更简单的语法或实用方法来帮助我们达到相同的效果?

Is there any simpler synatx or utility method to help us to achieve the same effect?

谢谢。

推荐答案

public static void CopyPropertiesTo<T, TU>(this T source, TU dest)
{
    var sourceProps = typeof (T).GetProperties().Where(x => x.CanRead).ToList();
    var destProps = typeof(TU).GetProperties()
            .Where(x => x.CanWrite)
            .ToList();

    foreach (var sourceProp in sourceProps)
    {
        if (destProps.Any(x => x.Name == sourceProp.Name))
        {
            var p = destProps.First(x => x.Name == sourceProp.Name);
            if(p.CanWrite) { // check if the property can be set or no.
                p.SetValue(dest, sourceProp.GetValue(source, null), null);
            }
        }

    }

}

这篇关于使用C#将属性值复制到另一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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