将类复制到具有完全相同属性的另一个类

时间:2014-04-03 21:50:33

标签: c# reflection recursion tree

我需要将所有属性从一个类复制到另一个类。我知道如果它们只是一个对象,如何复制属性,但如果它包含自己的列表则不知道。 例如,

    public class A
{
    public int ID { get; set; }
    public string name { get; set; }
    public List<A> Ass { get; set; }
}
public class B
{
    public int ID { get; set; }
    public string name { get; set; }
    public List<B> Bss { get; set; }
}

如果

中有自己的集合,我所拥有的不起作用
if (source != null && destination != null)
        {
            Type sourceType = source.GetType();
            Type destinationType = destination.GetType();
            foreach (PropertyInfo sourceProperty in sourceType.GetProperties())
            {
                PropertyInfo destinationProperty = destinationType.GetProperty(sourceProperty.Name);
                if (destinationProperty != null && sourceProperty.CanRead && destinationProperty.CanWrite)
                {
                    destinationProperty.SetValue(destination, sourceProperty.GetValue(source, null), null);
                }
            }
        }

有没有人知道将一切从一个类复制到另一个类的方法,即使它本身有一个相同类的List?我在想一些递归但不确定如何接近的东西。

0 个答案:

没有答案