C#中的自动设置属性

时间:2014-06-26 21:00:09

标签: c# getter-setter

我有一个名为Place的类,它使用getter和setter,如下所示:

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;
        }
    }
}

并说我想创建类Place的新实例:

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

设置Address属性时,如何自动触发Location变量的setter,以便自动对地址进行地理编码并自动设置GeoCoordinate对象?

3 个答案:

答案 0 :(得分:3)

您需要将Address从自动属性更改为&#34;常规&#34;一个(即由变量和getter / setter对组成的属性),如下所示:

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;
    }
}

答案 1 :(得分:1)

public string Address { get; set; }更改为

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

顺便说一下,这个代码在这里

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

将永远递归。你应该考虑重做那个。

答案 2 :(得分:1)

set语义对您正在做的事情没有任何意义(您甚至不使用value关键字)。在最坏的情况下,它使这段代码无意义:

obj.Location = someGeoCoordiante;

您可以轻松地将逻辑放在get篇中(而不是定义set)。当然,每次访问时都会重新运行计算。如果这是一个问题,仍然删除该集并让Address属性的setter重新计算本地存储的Location字段。