gpt4 book ai didi

c# - 如何在同一个类的main方法之外引用一个对象?

转载 作者:太空宇宙 更新时间:2023-11-03 13:28:02 26 4
gpt4 key购买 nike

在使用 C# 和图形库 SFML 创建游戏的过程中,我遇到了“名称‘fighter’在当前上下文中不存在”的错误。我不确定如何在 SFML 静态事件方法 MouseButtonPressed() 中引用该对象,因为它会返回上述错误。

我知道您可以像我在代码中所做的那样(并在下面注释掉)将对象声明为静态的。但是,在整个游戏中,将创建未知数量的对象,因此我认为您不会创建多个实例字段。什么是最好的方法?

相关代码:

namespace Game
{
public class Program
{
//I don't want to have to do this
//static Unit fighter;

Texture textureFighter;
static void MouseButtonPressed(object sender, MouseButtonEventArgs e)
{
if (e.Button == Mouse.Button.Left)
{
fighter.Move(new Vector2f(Mouse.GetPosition().X, Mouse.GetPosition().Y));
}
}
public static void Main()
{
Program myProgram = new Program();

myProgram.textureFighter = new Texture(@"resources\ship_fighter.png");

Unit fighter = new Unit(new Vector2f(100, 100), 0)
{
Texture = myProgram.textureFighter
};
...
}

}
}

最佳答案

我不确定这是否是您的意思,您可以试试这段代码吗?

namespace Game
{
public class Program
{
static Program myProgram = new Program();
Unit fighter;

Texture textureFighter;
static void MouseButtonPressed(object sender, MouseButtonEventArgs e)
{
if (e.Button == Mouse.Button.Left)
{
myProgram.fighter.Move(new Vector2f(Mouse.GetPosition().X, Mouse.GetPosition().Y));
}
}
public static void Main()
{
myProgram.textureFighter = new Texture(@"resources\ship_fighter.png");

myProgram.fighter = new Unit(new Vector2f(100, 100), 0)
{
Texture = myProgram.textureFighter
};
...
}

}
}

关于c# - 如何在同一个类的main方法之外引用一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21667453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com