lundi 28 septembre 2015

Common action executed for multiple getters

I'm trying to find a neat way to trigger a loading mechanism when one of several getters is first accessed. My first thoughts are about something like this:

public class Customer {
    private bool loaded = false;

    public int PK { get; set; }
    public string Email { get; set; }

    public string Name { get { if (!loaded) loadData(); return _name; } set { ... } }
    public string Street { get { if (!loaded) loadData(); return _street; } set { ... } }
    public string City { get { if (!loaded) loadData(); return _city; } set { ... } }
}

In short, in this example every Customer exists with its base data PK and Email until one of the other properties is accessed.

This would mean much duplicate code, increasing with the complexity of the class. Is there a way to create some kind of inheritance for these properties?

Something like this, but I don't think this is possible:

private void checkData() { if (!loaded) loadData(); }
public string Name:checkData { get; set; }
public string Street:checkData { get; set; }
public string City:checkData { get; set; }

Another way might be possible through reflection, but as I'm not experienced with it I don't know where to start here.

Any hints are deeply appreciated! ;-)





Aucun commentaire:

Enregistrer un commentaire