首页 热门资讯文章正文

如何在C#中复制不同对象的属性

热门资讯 2025年09月03日 10:37 2 admin

在 C# 开发中,我们经常需要在不同对象之间复制属性值,比如将 DTO 对象转换为实体对象,或者在相似但不同的类之间传递数据。本文将介绍几种常用的属性复制方法。

1. 手动赋值

最简单直接的方法是手动为每个属性赋值:

如何在C#中复制不同对象的属性

public class Source{    public int Id { get; set; }    public string Name { get; set; }    public DateTime CreateTime { get; set; }}public class Target{    public int Id { get; set; }    public string Name { get; set; }    public string Description { get; set; }}// 手动复制属性public static Target CopyManual(Source source){    if (source == null)        return null;            return new Target    {        Id = source.Id,        Name = source.Name        // Target的Description属性在Source中没有,所以不复制    };}

优点:简单直观,性能好,可控制复制过程
缺点:属性多时代码冗长,维护成本高

1. 使用反射

通过反射可以实现通用的属性复制方法,适用于各种对象:

如何在C#中复制不同对象的属性

public static void CopyProperties(object source, object target){    var sourceProperties = source.GetType().GetProperties();    var targetProperties = target.GetType().GetProperties();    foreach (var sourceProp in sourceProperties)    {        foreach (var targetProp in targetProperties)        {            if (sourceProp.Name == targetProp.Name &&            sourceProp.PropertyType == targetProp.PropertyType &&            targetProp.CanWrite)            {                var value = sourceProp.GetValue(source)
;                targetProp.SetValue(target, value);                break;            }        }    }}// 使用Source source = new Source { Id = "1", Name ="张三" , CreateTime ="张三",CreateTime = DateTime.Now };TargetClass target = new TargetClass();CopyProperties(source, target);

优点:通用性强,一次编写多处使用
缺点:反射性能相对较差,复杂类型处理需要额外逻辑

发表评论

泰日号Copyright Your WebSite.Some Rights Reserved. 网站地图 备案号:川ICP备66666666号 Z-BlogPHP强力驱动