0

ここでの私の考えは、テキストベースのアドベンチャーゲームを作成することです。

メインクラスでクラスを使用しようとしています。私がしようとしている間、それは私にエラーを与えます:

「MyAdventure.Window」は「タイプ」ですが、「変数」のように使用されます

これを解決する方法がわかりません。クラスの新しいインスタンスを作成しようとしましたが、機能しなかったようです。私はこれにかなり慣れていませんが、誰か助けてもらえますか?

前もって感謝します。

これが私のメインクラス(Program.cs)のコードです:

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

namespace MyAdventure
{
class Program
{
    static void Main(string[] args)
    {

        Console.WriteLine("You cannot feel your body. You don't know where you are.\nThe room you're in is dark. You cannot see much.");
        Console.WriteLine("You decide to stand up, and take a look around. You see a door and a window.\nWhich do you check out first?");
        Console.WriteLine("A. Window\nB. Door");

        string userInput = Console.ReadLine();
        //Window theWindow = new Window();

        if (userInput.StartsWith("A", StringComparison.CurrentCultureIgnoreCase))
        {
            Window();
        }
        else if (userInput.StartsWith("B", StringComparison.CurrentCultureIgnoreCase))
        {
            Console.WriteLine("You chose the door.");
        }

        Console.ReadKey();

    }
}

}

そして、これは他のクラスWindow.csの(これまでの)コードです:

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

namespace MyAdventure
{
public class Window
{
    static void theWindow()
    {

        Console.WriteLine("You approach the window.");
        Console.ReadKey();

    }
}

}

4

3 に答える 3

3

クラスの静的メソッドを呼び出すための正しい構文は次のとおりです。

   if (userInput.StartsWith("A", StringComparison.CurrentCultureIgnoreCase))
   {
        Window.theWindow();
   }

クラスの名前だけを使用することはできませんが、呼び出す静的メソッドを指定する必要があります(潜在的に多くのメソッドからの1つ)

静的メソッドの呼び出し

また、メソッド'theWindow'はパブリックにする必要があります。そうしないと、クラス内でデフォルトでプライベートになります。

ネストされたクラスと構造体を含む、クラスメンバーと構造体メンバーのアクセスレベルは、デフォルトでプライベートです。

public static void theWindow()
{
    Console.WriteLine("You approach the window.");
    Console.ReadKey();
}
于 2012-11-06T11:08:31.237 に答える
0

theWindow()静的メソッドです。ClassName.MethodName()あなたの場合、静的メンバーはのように呼ばれますWindow.theWindow()

あなたがやったとき、あなたはクラスWindow theWindow = new Window();のインスタンスを作成していました。Window静的メンバーは、クラスのインスタンスからアクセスできません。

staticインスタンスからそのメソッドを呼び出すには、修飾子を削除する必要があります

public class Window
{
    public void theWindow()
    {
        Console.WriteLine("You approach the window.");
        Console.ReadKey();

    }
}

使用法

Window w = new Window(); //creating an instance of Window
w.theWindow();
于 2012-11-06T11:10:04.023 に答える
0

あなたは電話する必要があるかもしれません

....
...
if (userInput.StartsWith("A", StringComparison.CurrentCultureIgnoreCase))
{
      Window.theWindow();
}
...
...
于 2012-11-06T11:08:11.000 に答える