这是我的类声明
public class PlacesAPIResponse
{
public string formatted_address { get; set; }
public Geometry geometry { get; set; }
public Location location { get; set; }
public string icon { get; set; }
public Guid id { get; set; }
public string name { get; set; }
public string reference { get; set; }
public string[] types { get; set; }
}
public class Geometry
{
Location location { get; set; }
}
public class Location
{
public double lat { get; set; }
public double lon { get; set; }
}
当我尝试像这样访问它时,我得到了“由于保护级别而无法访问”
PlacesAPIResponse response = new PlacesAPIResponse();
string lon = response.geometry.location.lon;
我做错了什么?
请您参考如下方法:
您需要将您的 Geometry.location 字段声明为公共(public)字段:
public class Geometry
{
public Location location;
}
默认情况下,当您没有显式声明类成员的访问修饰符时,假定它的可访问性是 private。
来自 C# 规范部分 10.2.3 Access Modifiers :
When a class-member-declaration does not include any access modifiers, private is assumed.
顺便说一句,您也可以考虑将其设为属性(除非它是 mutable struct )
编辑:此外,即使您修复了访问问题,Location.lon 也被声明为 double 但您隐式地将其分配给了 string 。您还需要将其转换为字符串:
string lon = response.geometry.location.lon.ToString();
