Question

J'ai une méthode où je passe dans deux objets, qui ont les mêmes noms de propriété, et j'utilise la réflexion pour obtenir les valeurs d'un objet et définir les valeurs de l'autre. Mon problème est quand je tombe sur une propriété qui est une collection, l'original est EntityCollection et celui d'obtenir ensemble est ObservableCollection, et je vais évidemment lancer une erreur de casting lorsque je tente de définir la valeur.

Alors, comment pourrais-je aller à ce sujet? Je pensais que d'une façon serait d'obtenir l'instance de la propriété EntityCollection et dans une utilisation en boucle Activator.CreateInstance () pour ajouter un nouvel élément à la ObservableCollection. Mais je tombe sur une autre question de savoir comment obtenir l'instance d'origine.

Je serais très reconnaissante pour un aperçu de ce dilemme. Je vais poster le code pour la méthode que je travaille avec. Il ne fonctionne pas actuellement, surtout je l'ai posté juste pour une référence. Alors s'il vous plaît ne dirigez pas l'évidence. Merci à l'avance.

protected void SetValues(Object thisObject, Object entity)
{
    PropertyInfo[] properties = entity.GetType().GetProperties();
    foreach (PropertyInfo property in properties)
    {
        var value = property.GetValue(entity, null);
        var thisObjectsProperty = thisObject.GetType().GetProperty(property.Name);

        if (thisObjectsProperty != null && value != null)
        {
            if (thisObjectsProperty.PropertyType.GetInterface("ICollection", true) != null                && thisObjectsProperty.PropertyType.GetGenericArguments().Count() > 0)
            {
                Type genericType = thisObjectsProperty.PropertyType.GetGenericArguments()[0];
                Type entityCollectionType = property.PropertyType;
                Type thisCollectionType = thisObjectsProperty.PropertyType;

                IList entityCollection = (IList)Activator.CreateInstance(entityCollectionType.MakeGenericType(genericType));
                IList observableCollection = (IList)Activator.CreateInstance(thisCollectionType.MakeGenericType(genericType));

                foreach (var item in entityCollection)
                {
                    String typeString = String.Concat("RulesGenerator.DependencyObjects.", genericType.Name);
                    Type newItemType = Type.GetType(typeString, false, true);
                    if (newItemType != null)
                    {
                        var newItem = Activator.CreateInstance(newItemType);
                        SetValues(newItem, item);
                        observableCollection.Add(newItem);
                    }
                }
            }
            else
                thisObjectsProperty.SetValue(thisObject, value, null);
        }
    }
}
Était-ce utile?

La solution

Mettre en oeuvre l'interface ICloneable pour fournir une copie en profondeur. Vous devriez être en mesure de trouver des exemples, mais voici un point de départ:

http: // msdn. microsoft.com/en-us/library/system.icloneable%28v=VS.71%29.aspx

http://en.csharp-online.net/ICloneable

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;


public class testMain : ICloneable
{

    private string m_TestProp;

    private List<Record> m_Items = new List<Record>();
    public string TestProp
    {
        get { return m_TestProp; }
        set { m_TestProp = value; }
    }

    public List<Record> Items
    {
        get { return m_Items; }
    }


    public object Clone()
    {

        testMain cpy =(testMain) this.MemberwiseClone();

        foreach (Record rec in this.Items)
        {
            Record recCpy = (Record)rec.Clone();
            cpy.Items.Add(recCpy);
        }

        return cpy;
    }

}

public class Record : ICloneable
{

    private string m_TestProp;

    public string TestProp
    {
        get { return m_TestProp; }
        set { m_TestProp = value; }
    }

    public object Clone()
    {
        return this.MemberwiseClone();
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top