编译时间错误 - 构件不能与实例引用来访问(Compile time error - member

2019-09-29 14:48发布

我是一个新的尝试理解类,以及如何类工作。 我建立一个小控制台程序,我目前的工作在我题为“LineItem.cs”,因为它会处理收据上的行项目,我试图让我的控制台应用程序生成我“class.cs”文件。

问题:会员“A070_ _CashRegister.Program.receipt()”不能以一个实例引用来访问; 与类型名称,而不是限定它。 (错误行:#21 /列#13)

我以为我已经做到了这线#21,当我进入“this.color =价格;

码:

using System;
namespace a070___Classes___CashRegister
{
  class LineItem     // Class name is singular
                     // receipt might be better name for this class?
  {
    /// Class Attributes
    private String product;     // constructor attribute
    private String description;
    private String color;
    private double price;
    private Boolean isAvailable;

    // constructor called to make object => LineItem
    public LineItem(String product, String description, String color, int price, Boolean isAvailable)
    {
        this.product = product;
        this.description = description;
        this.color = color;
        this.price = price;
        this.isAvailable = isAvailable;// might want to do an availability check
    }

    //Getters
    public String GetProduct() {return product;}
    public String GetDescription(){return description;}//Send description
    public String GetColor() {return color;}

    //Setter
    public void SetColor(string color)//we might want to see it in other colors if is option
    { this.color = color; } //changes object color 
  }
}

主文件,该文件将调用类:

using System;

namespace a070___Classes___CashRegister
{
  class Program
  {
    static void receipt()
    { 
    //stuff goes here - we call various instances of the class to generate some receipts
    }

    static void Main(string[] args)
    {
        //Program CashRegister = new Program();
        //CashRegister.receipt();

        //Program CashRegister = new Program();
        //CashRegister.receipt();

        receipt();// Don't need to instantiate Program, console applications framework will find the static function Main
        //unless changed your project properties.
        //Since reciept is member od Program and static too, you can just call it directly, without qualification.
    }
  }
} 

Answer 1:

Program CashRegister = new Program();
CashRegister.receipt();

应该

Program.receipt();

要不就

receipt();

你并不需要实例Program ,控制台应用程序框架将找到static function Main(...并称之为魔法,除非你已经改变了你的项目属性。

由于receipt是其成员的Programstatic太大,你可以直接调用它,没有资格。


receipt()函数是static ,但是你想从一个实例调用它。

您还没有显示任何地方receipt声明或者您拨打电话,所以我不能帮助更多。

也许你有一个行代码,在某处它那里是一个表达式一样,

... this.receipt() ...

要么

... yourInstance.receipt() ...

而应该是,

... Type.receipt() ...


Answer 2:

你不能用一个实例访问静态方法。

所有你需要做的是,像这样的类来访问它:

LineItem.receipt();

注意:您还没有提到其他的代码,所以我不知道在哪里的方法收据定位所以我认为它是在LineItem类。

还有一两件事,最好是拨打以大写字母方法 - 收据。



文章来源: Compile time error - member cannot be accessed with an instance reference