简体   繁体   中英

Auto setting properties in C#

I have a class called Place that uses getters and setters like so:

public class Place
{
    public string Address { get; set; }
    public GeoCoordinate Location
    {
        set
        {
            // geocode Address field and receive Geocoding response, initializing a new instance of GeoCoordinate class - my attempt below..
            IGeocoder geocoder = new GoogleGeocoder();
            IEnumerable<Address> matchedAddresses = geocoder.Geocode(this.Address);
            this.Location = new GeoCoordinate(matchedAddresses.Cast<Address>().First().Coordinates.Latitude, matchedAddresses.Cast<Address>().First().Coordinates.Longitude);
        }
        get
        {
            return this.Location;
        }
    }
}

And say I want to create a new instance of the class Place like so:

    Place thePlace = new Place()
    {
        Address = "123 Fake Street, London"
    };

How would I automatically trigger the setter for the Location variable when the Address property is set so that the address fed in is automatically geocoded and the GeoCoordinate object is set automatically?

You would need to change the Address from an auto-property to a "regular" one (ie a property composed from a variable and a getter/setter pair), like this:

private string address;
public string Address {
    get {return address;}
    set {
        // Prepare the location
        GeoCoordinate loc = GetGeoCoordinateFromAddress(value);
        // Store address for future reference
        address = value;
        // Setting the location by going through the property triggers the setter
        Location = loc;
    }
}

Change public string Address { get; set; } public string Address { get; set; } public string Address { get; set; } to

private string _address;
public string Address
{
    get { return _address; }
    set
    {
        // code to set geocoder
        _address = value;
    }
}

By the way, this code here

public GeoCoordinate Location
{
    ...
    get
    {
        return this.Location;
    }
}

will recurse forever. You should think about reworking that.

The set semantic doesn't make any sense for what you are doing (you aren't even using the value keyword). At worst, it makes this code nonsense:

obj.Location = someGeoCoordiante;

You could easily just put the logic in the get piece (and not define a set ). Of course this will re-run your calculation every time you access it. If that is a problem, still remove the set and have the setter for the Address property recalculate the locally stored Location field.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM