1

我是一个试图理解类和类如何工作的新手。我正在构建一个小型控制台程序,目前正在处理我的名为“LineItem.cs”的“class.cs”文件,因为它将处理我试图让我的控制台应用程序生成的收据上的行项目。

问题:无法使用实例引用访问成员“A070_Classes_CashRegister.Program.receipt()” 而是用类型名称来限定它。(错误行:#21/列#13)

当我输入 'this.color = price;

代码:

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.
    }
  }
} 
4

2 回答 2

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

应该

Program.receipt();

要不就

receipt();

您不需要实例化Program,使用控制台应用程序,框架会static function Main(...通过魔术找到并调用它,除非您更改了项目属性。

既然receiptProgramand statictoo 的成员,你可以直接调用它,不加限定。


receipt()函数是static,但您正在尝试从实例调用它。

您没有显示在哪里receipt声明或从哪里调用它,所以我无法提供更多帮助。

也许您有一行代码,其中某处有一个表达式,例如,

... this.receipt() ...

或者

... yourInstance.receipt() ...

但应该是,

... Type.receipt() ...
于 2013-11-08T17:14:10.390 回答
0

您不能使用实例访问静态方法。

您需要做的就是使用这样的类访问它:

LineItem.receipt();

注意:您没有提到其他代码,所以我不知道方法接收的位置,所以我假设它在 LineItem 类中。

还有一件事,最好用大写字母调用方法 - 收据。

于 2013-11-08T17:16:36.037 回答