簡體   English   中英

如何從主 class 調用 object 到另一個 C#

[英]How to call an object from Main class to another C#

我正在嘗試將 object 從一個 class 調用到 C# 中的另一個。 我該怎么做呢?

這是我的代碼片段:

public bool IsPositionFree(int x, int y)
{
    if (x < 0 || y < 0 || x >= Cols || y >= Rows)
    {
        return false;
    }
    return Maze[y, x] == " " || Maze[y, x] == "E" || *** Here is where I want to check if y,x is equal to my treasure object (Treasure t1) that I have drawn to my screen *** ;
}

在我的主程序中,我創建了一個 object,這就是我要調用的其他 class

public static Treasure t1;

Treasure t1 = new Treasure(1, 3);

我的寶藏 class 是 -

class Treasure
{
    public int x { get; set; }
    public int y { get; set; }
    public string Gold;
    private ConsoleColor TreasureColour;
    private int TreasureValue = 100;

    public Treasure(int initialx , int initialy)
    {
        x = initialx;
        y = initialy;
        Gold = "T";
        TreasureColour = ConsoleColor.Yellow;       
    }

    public void DrawTreasure()
    {       
        ConsoleColor Color = TreasureColour;
        Console.SetCursorPosition(x, y);
        Console.Write(Gold);

    }
}

假設您的Treasure t1Program ... 中定義,您的回報將如下所示:

            
            return Maze[y, x] == " " || Maze[y, x] == "E" || (x == Program.t1.x && y == Program.t1.y);

如果它們在同一個命名空間中,您可以直接在一行中鍵入 ClassName。 如果您不必導入 class 目標,例如:

“使用 MyProject.Classes”

你有A類:

namespace ExampleNamespace
{
  public class ClassA 
  {
      public string  fieldA  {get;set;} 

      public void DoSomething(int variable)
      {
         //doing something
      }
  
   }
}

你有使用 ClassA 的 ClassB:


using ExampleNamespace;

public class ClassB
{
    public string randomField  {get;set;} 

    public void DoSomethingButBetter(int variable)
    {
         ClassA classA = new ClassA();
         classA.DoSomething(1);
    }

}


將此添加到您的寶藏 class:

public bool isLocationMatch(int x, int y) => x == this.x && y == this.y;

然后你有一些工作要做。 您必須考慮如何IsPositionFree知道t1 但是您還沒有發布 [mcve],所以我很難准確地說出您將如何使用新方法。 您可能可以自己解決。

該調用類似於t1.isLocationMatch(x, y)


從設計的角度來看,您可能需要考慮維護 X/Y 平面的 model。 object或基本 class 的二維數組?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM