mercredi 22 avril 2015

Is there a simple way to generically parse data from strings for child class properties of differing types in C#?

I have a base class

abstract public class containerClass {
    protected containerClass () {
        // do stuff
    }

    abstract protected void parseData() {
        // do the stuff I'm mentioning later
    }

}

and child classes

public class childClassOne : containerClass {
    public childClassOne () : base () {
        var1S = "99";
        var2S = "88.3";
        var3S = "2015-04-22T15:55:25.2625065-07:00";
    }
    public int var1 {get: protected set;}
    public double var2 {get: protected set;}
    public DateTime var3 {get: protected set;}

    public string var1S {get: protected set;}
    public string var2S {get: protected set;}
    public string var3S {get: protected set;}
}

and

public class childClassTwo : containerClass {
    public childClassTwo () : base () {
        var1S = "99.22";
        var2S = "88.3";
        var3S = "43.44";
    }
    public double var1 {get: protected set;}
    public double var2 {get: protected set;}
    public double var3 {get: protected set;}

    public string var1S {get: protected set;}
    public string var2S {get: protected set;}
    public string var3S {get: protected set;}
}

What I want to do is define parseData in the parent class to iterate through the properties when it's called by a child class and parse the strings for relevant data.

Order needs to be preserved. And the strings might be external data, not properties or fields of these classes.

My current thoughts in pseudo-code are something like:

for (property prop in thisClass)
{
    typeof(prop) temp;
    if (typeof(prop).tryParse(var1S, temp))
        prop = temp;
}

All of the class I'm looking at have a tryParse method with two input variables. Can what I'm trying to do work? If so, how can I iterate over the properties in an unambiguous order?





Aucun commentaire:

Enregistrer un commentaire