c# - 由于保护级别而无法访问类属性

标签 c# class oop access-levels

这是我的类声明

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();

关于c# - 由于保护级别而无法访问类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16719022/

相关文章:

C#:用于启用实现和覆盖的接口(interface)和抽象

c# - 是否可以设计一个 C# 类,在通过反射查询时将其自身标记为正 IsValueType 和正 IsClass?

c# - 多线程安全日志记录

javascript - 在javascript类中创建方法事件

java - 我可以在公共(public)方法中声明私有(private)变量吗?

c# - 更改属性时遇到问题

c++ - 从派生类访问基类中的 protected 成员

javascript - ES6 类变量替代方案

file - OOP 中处理不同文件类型的设计模式

objective-c - 为 C 程序员学习 OO