繁体   English   中英

C#中的自动设置属性

[英]Auto setting properties in C#

我有一个名为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"
    };

当设置了地址属性时,如何自动触发位置变量的设置器,以便自动对输入的地址进行地理编码并自动设置GeoCoordinate对象?

您需要将Address从自动属性更改为“常规”地址(即,由变量和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;
    }
}

更改public string Address { get; set; } public string Address { get; set; } 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;
    }
}

将永远递归。 您应该考虑重新设计。

set语义对您的工作没有任何意义(您甚至没有使用value关键字)。 最糟糕的是,它使这段代码变得毫无意义:

obj.Location = someGeoCoordiante;

您可以轻松地将逻辑放入get块中(而不定义set )。 当然,这将在您每次访问计算时重新运行。 如果存在问题,请仍然删除该设置,并让Address属性的设置器重新计算本地存储的Location字段。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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