Im trying to build an application where the properties of the classes are set based on the values in som XML files.
Some of the classes has properties consisting of a list of of it's children. Due to the way i made this program, the properties has to be set via propertyinfo classes. My problem is that i have trouble with fetcing the list of children (ICollection in Derived2).
It must be cast to a generic list (ICollection OR HashSet), so i dont have to copy paste the same setChild method in each derived class.
I've tried casting the GetValue return value to either ICollection, HashSet or IENumerable, none worked.
Maybe the solution could be to use another method of the PropertyInfo class?
A somewhat simplified code example code:
public interface Superclass
{}
public class Derived1 : Superclass {}
public class Derived2 : Superclass
{
public Derived2()
{
PatientForloeb = new HashSet<Derived1>();
}
public virtual ICollection<Derived1>Derived1{ get; set; }
}
class Program
{
static void Main(string[] args)
{
List<Derived1> children = new List<Derived1>();
children.Add(new Derived1());
var parent = new Derived2();
setChild(parent, children);
}
private static void setChild(Superclass parent, List<Derived1> children)
{
foreach (var child in children)
{
var p = (parent.GetType().GetProperty(child.GetType().Name)); // This is ugly, should be based on type not name, but it works for my app.
var pi = p.GetValue(parent) as HashSet<Superclass>; ///////////<-------This gives null. This is the problem.
pi.add(child);
}
}
}