Domanda

here are my class declarations

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

when i try to access it like this, but i get an "inaccessible due to protection level"

PlacesAPIResponse response = new PlacesAPIResponse();
string lon = response.geometry.location.lon;

what could i be doing wrong ?

È stato utile?

Soluzione 2

Make location public. It is private by default.

public class Geometry
{
    public Location location;
}

And you can access lon as double

PlacesAPIResponse response = new PlacesAPIResponse();
double lon = response.geometry.location.lon;

Altri suggerimenti

You need to declare your Geometry.location field as public:

public class Geometry
{
    public Location location;
}

By default, when you do not explicitly declare the access modifier for a class member, the assumed accessibility for it is private.

From the C# Specification section 10.2.3 Access Modifiers:

When a class-member-declaration does not include any access modifiers, private is assumed.


As an aside, you may also consider making it a property (unless it's a mutable struct)

EDIT: In addition, even when you fix the access issue, Location.lon is declared as a double but you are implicitly assigning it to a string. You will need to convert it to a string as well:

string lon = response.geometry.location.lon.ToString();

The location property of Geometry doesn't specify an accessibility level. The default level is private.

Geometry.location has no access modifier so it is private by default

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top