1

私は、クラスとクラスがどのように機能するかを理解しようとしている新しい人です。私は小さなコンソール プログラムを作成しており、現在、コンソール アプリケーションに生成させようとしているレシートの項目を処理するため、「LineItem.cs」というタイトルの「class.cs」ファイルに取り組んでいます。

問題: メンバー 'A070_ Classes _CashRegister.Program.receipt()' にインスタンス参照でアクセスできません。代わりに型名で修飾してください。(エラー行: #21/列 #13)

「this.color = price;」と入力したとき、21行目でこれを行ったと思いました。

コード:

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(...、プロジェクトのプロパティを変更していない限り、フレームワークが魔法のように を見つけて呼び出します。

and tooreceiptのメンバーなので、修飾せずに直接呼び出すことができます。Programstatic


receipt()関数はありますstaticが、インスタンスから呼び出しようとしています。

どこreceiptで宣言されているか、どこから呼び出しているかが表示されていないため、これ以上のことはできません。

おそらく、コード行があり、そのどこかに次のような式があります。

... this.receipt() ...

また

... yourInstance.receipt() ...

しかし、

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

インスタンスで静的メソッドにアクセスすることはできません。

あなたがする必要があるのは、次のようなクラスでそれにアクセスすることだけです:

LineItem.receipt();

注: 他のコードについて言及していないため、メソッドの領収書がどこにあるのかわからないため、LineItem クラスにあると想定しています。

もう1つ、メソッドを大文字で呼び出す方が良い - Receipt.

于 2013-11-08T17:16:36.037 に答える