简体   繁体   English

Getters Setters自动属性问题

[英]Getters Setters Autoproperty issue

Having an issue with autoproperty. 对自动属性有疑问。 Here's snippet from my class: 这是我班上的片段:

 class Car
{
    string brand;
    string model;
    Engine CarEngine {get; set;}

Now the class Engine: 现在类引擎:

class Engine
{
    double FuelCap { get; }
    double fuelCapDefault = 50;
    double FuelCount { get; set;}
    double engineCap;

I created an object with constructor: 我用构造函数创建了一个对象:

  public Car(string brand, string model, double engineCap, double FuelCount, double FuelCap)
    {
        this.brand = brand;
        this.model = model;
        this.CarEngine = new Engine(engineCap, FuelCount, FuelCap);

    }

and the constructor for Engine: 以及Engine的构造函数:

public Engine(double engineCap, double FuelCount, double FuelCap)
    {
        this.engineCap = engineCap;
        this.FuelCount = FuelCount;
        this.FuelCap = FuelCap;
    }

I've created an object with: 我用以下方法创建了一个对象:

 Car car = new Car(x, y, z, a, b);

Now to the main point, finally: 现在到重点,终于:

I'm trying to access car.CarEngine.FuelCount in my Main Program to get the value, but Visual doesn't even suggest me the CarEngine. 我试图在主程序中访问car.CarEngine.FuelCount以获得值,但是Visual甚至没有建议我使用CarEngine。 I'm new to the whole autoproperty stuff. 我是整个汽车知识的新手。 What did I do wrong? 我做错了什么?

All the properties that you have declared doesn't have any modifier , so by default they are private . 您已声明的所有属性都没有任何modifier ,因此默认情况下它们是private This means that they can only be accessed within the declaring class. 这意味着只能在声明类中访问它们。

Mark them public will solve the problem. 标记他们为public将解决问题。

All types and type members have an accessibility level, which controls whether they can be used from other code in your assembly or other assemblies. 所有类型和类型成员都有一个可访问性级别,该级别控制是否可以从程序集中的其他代码或其他程序集中使用它们。 You can use the following access modifiers to specify the accessibility of a type or member when you declare it: 在声明类型或成员时,可以使用以下访问修饰符来指定它的可访问性:

public The type or member can be accessed by any other code in the same assembly or another assembly that references it. public该类型或成员可以由同一程序集中或引用它的另一个程序集中的任何其他代码访问。

private The type or member can be accessed only by code in the same class or struct. private类型或成员只能由相同类或结构中的代码访问。

For the full list see Access Modifiers (C# Programming Guide) 有关完整列表,请参见访问修饰符(C#编程指南)

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

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