实体2赋值给实体1

using System;
using System.Reflection;

public static class PropertyCopier
{
    /// <summary>
    /// 将源对象的值复制到目标对象,只复制具有相同名称的属性值。
    /// </summary>
    /// <typeparam name="T1">目标对象的类型</typeparam>
    /// <typeparam name="T2">源对象的类型</typeparam>
    /// <param name="destination">目标对象</param>
    /// <param name="source">源对象</param>
    public static void CopyProperties<T1, T2>(T1 destination, T2 source)
        where T1 : class
        where T2 : class
    {
        if (destination == null) throw new ArgumentNullException(nameof(destination));
        if (source == null) throw new ArgumentNullException(nameof(source));

        Type sourceType = source.GetType();
        Type destinationType = destination.GetType();

        PropertyInfo[] sourceProperties = sourceType.GetProperties(BindingFlags.Public | BindingFlags.Instance);

        foreach (PropertyInfo sourceProperty in sourceProperties)
        {
            PropertyInfo destinationProperty = destinationType.GetProperty(sourceProperty.Name, BindingFlags.Public | BindingFlags.Instance);
            if (destinationProperty != null && destinationProperty.CanWrite)
            {
                object value = sourceProperty.GetValue(source);
                destinationProperty.SetValue(destination, value);
            }
        }
    }
}

// 示例实体类
public class Entity1
{
    public int Id { get; set; }
    public string Name { get; set; }
    public double Value { get; set; }
}

public class Entity2
{
    public int Id { get; set; }
    public string Name { get; set; }
    public double Value { get; set; }
    public string AdditionalProperty { get; set; }
}

// 测试代码
public class Program
{
    public static void Main()
    {
        Entity2 entity2 = new Entity2
        {
            Id = 1,
            Name = "Entity2",
            Value = 100.0,
            AdditionalProperty = "This is Entity2"
        };

        Entity1 entity1 = new Entity1();

        PropertyCopier.CopyProperties(entity1, entity2);

        Console.WriteLine($"Entity1 Id: {entity1.Id}");
        Console.WriteLine($"Entity1 Name: {entity1.Name}");
        Console.WriteLine($"Entity1 Value: {entity1.Value}");
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值