.net解决, A对象赋值给B对象,修改B对象,A对象也变化了

你可以使用C#编程语言来编写一个通用的扩展方法,用于将一个对象的值复制到另一个对象,并且修改目标对象的属性时原始对象不受影响。

以下是一个示例代码:

using System;
using System.Reflection;

public static class ObjectExtensions
{
    public static void CopyPropertiesTo(this object source, T destination)
    {
        if (source == null)
            throw new ArgumentNullException(nameof(source));

        if (destination == null)
            throw new ArgumentNullException(nameof(destination));

        Type sourceType = source.GetType();
        Type destinationType = typeof(T);

        PropertyInfo[] sourceProperties = sourceType.GetProperties();
        PropertyInfo[] destinationProperties = destinationType.GetProperties();

        foreach (var sourceProperty in sourceProperties)
        {
            foreach (var destinationProperty in destinationProperties)
            {
                if (sourceProperty.Name == destinationProperty.Name && 
                    sourceProperty.PropertyType == destinationProperty.PropertyType &&
                    destinationProperty.CanWrite)
                {
                    object value = sourceProperty.GetValue(source);
                    destinationProperty.SetValue(destination, value);
                    break;
                }
            }
        }
    }
}

可以按照以下方式使用该扩展方法:

public class A
{
    public int Foo { get; set; }
    public string Bar { get; set; }
}

public class B
{
    public int Foo { get; set; }
    public string Bar { get; set; }
}

public class Program
{
    static void Main()
    {
        A a = new A { Foo = 42, Bar = "Hello" };
        B b = new B();

        a.CopyPropertiesTo(b);

        Console.WriteLine($"a: Foo = {a.Foo}, Bar = {a.Bar}");
        Console.WriteLine($"b: Foo = {b.Foo}, Bar = {b.Bar}");
        
        b.Foo = 100; // 修改b对象的属性值
        
        Console.WriteLine($"a: Foo = {a.Foo}, Bar = {a.Bar}");
        Console.WriteLine($"b: Foo = {b.Foo}, Bar = {b.Bar}");
    }
}

你可能感兴趣的:(.net,java,开发语言)