1

このクラスを考えてみましょう:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Game.Items
{
    class Item
    {
        private string name;
        public string Name
        {
            get { return this.name; }
        }

        private string description;
        public string Description
        {
            get { return this.description; }
        }

        public Item(string name, string description)
        {
            this.name = name;
            this.description = description;
        }

        public override string ToString()
        {
            return this.name;
        }
    }
}

次に、次のような新しいオブジェクトを作成します。

Item item1 = new Item("Item1", "Description...");

問題は、getter メソッドを使用してオブジェクトのプロパティにアクセスできないことです。つまり、これは機能しません。

Console.WriteLine(item1.Name);
Console.WriteLine(item1.Description);
Console.ReadLine();

「動作しない」とは、「デバッグの開始」をクリックすると、コンソールウィンドウが表示されますが、何も表示されず、空白です。ただし、これは正常に機能します。

Console.WriteLine(item1); // ToString()
Console.ReadLine();

私は何を間違っていますか?

リチャード

4

2 に答える 2

3

私にとってはうまくいきます:

using System;

namespace Application
{
    class Test
    {
        static void Main()
        {
            Item item1 = new Item("Item1", "Description...");
            Console.WriteLine(item1.Name);
            Console.WriteLine(item1.Description);
        }
    }
}

(あなたのクラスもそこにあります。)

「これはうまくいかない」と言うとき、正確には何がうまくいかないのですか?

于 2009-04-25T13:04:38.437 に答える
0

「アイテム」が含まれているプロジェクトとは異なるプロジェクトでメイン クラスを操作していますか? もしそうなら、

  • 他のプロジェクトを参照する
  • Item クラスを public としてマークする

    public class Item {
        // your code
    }
    

または、この方法でアクセスして、問題が名前空間に関連しているかどうかを確認することもできます

Console.WriteLine(Application.item1.Name);
Console.WriteLine(Application.item1.Description);

また、実行後に一時停止します。そうしないと、コンソール ウィンドウに何も表示されなくなります。

Console.ReadLine();

最後のコメントによると、using 句も確認してください。次に、Item クラスを使用しようとしているファイルの先頭で using 句を使用する必要があります。

using Game;
于 2009-04-25T13:08:26.040 に答える