mardi 5 juillet 2016

How to fix null subclasses instances with reflection

I have a main instance storing various subclasses instances with options inside.

Class MainClass
{
    public bool b;
    public int i;
    public List l = new List();

    Class SubClass1
    {
        ...
    }
    public SubClass1 sub1 = new SubClass1();

    Class SubClass2
    {
        ...
    }
    public SubClass2 sub2 = new SubClass2();
}

now, when starting all class are correctly instatiated, then some options are set, and the result is serialized.

The problem arises when (for various reasons) I have to change name of the instances. E.g. SubClass2---->SubClassB therefore when de-serializing SubClassB is obviously null.

So I have to fix this drawback and I have tought about reflection. Something like [pseudocode]

foreach(var subclass in MainClass)
{
    if(subclass is null)
    {
        Type subClassType = typeof(subclass);
        subclass = new subClassType();
    }
}

Thank you in advance for any help.





Aucun commentaire:

Enregistrer un commentaire