[英]Defining a class property with type void (not a method)
I'm trying to build a class called GameObject (for consoleApplication game), and that GameObject should have a function "onFrame" that is called, let's say, every 0.1 seconds. 我正在尝试建立一个名为GameObject的类(用于consoleApplication游戏),并且GameObject应该具有一个名为“ onFrame”的函数,比方说,每0.1秒调用一次。
But the catch is, that this function (void) should be unique for every gameObject - let's say I have GameObject: G1, G2. 但是要注意的是,对于每个gameObject来说,该函数(void)应该是唯一的-假设我有GameObject:G1,G2。 G1 will increase a variable by 1 in it's onFrame, and G2 will print something to the console (just examples). G1将在其onFrame中将变量增加1,而G2将在控制台上打印一些内容(仅作为示例)。
Is it possible to do that? 有可能这样做吗?
I tried doing that in this way: 我尝试过这种方式:
class GameObject
{
public void onFrame;
public GameObject (void of) //constructor
{
onFrame = of;
Thread t = new Thread(runOnFrame);
t.isBackgroundThread = true;
t.Start();
}
protected void runOnFrame ()
{
while (true)
{
Thread.Sleep(100);
if (onFrame != null) onFrame(); //EDIT: that (0) was typed by mistake
}
}
}
And the main function: 和主要功能:
public static int i = 0;
static void Main (string[] args)
{
GameObject G1 = new GameObject(new void (){
i++;
});
GameObject G2 = new GameObject(new void () {
Console.WriteLine("OnFrame is being called!");
})
}
But it doesn't seem like being the right way to do that... Is it possible? 但这似乎不是正确的方法……可能吗? And how do I do that? 我该怎么做?
What you're looking for is an Action
, which is the same as a void
delegate: 您正在寻找的是Action
,它与void
委托相同:
class GameObject
{
public Action onFrame;
public GameObject (Action of) //constructor
{
onFrame = of;
Thread t = new Thread(runOnFrame);
t.isBackgroundThread = true;
t.Start();
}
protected void runOnFrame ()
{
while (true)
{
Thread.Sleep(100);
if (onFrame != null) onFrame();
}
}
}
However I would suggest using a Timer
instead of calling thread.Sleep
in a continuous loop. 但是,我建议使用Timer
而不是在连续循环中调用thread.Sleep
。
One way to pass in a delegate is to use lambda syntax: 传递委托的一种方法是使用lambda语法:
GameObject G1 = new GameObject(() => i++ );
The ()
is a placeholder for an empty input parameter set: ()
是空输入参数集的占位符:
What you need is a delegate. 您需要的是一名代表。
Your "onFrame" definition should look something like this: 您的“ onFrame”定义应如下所示:
public delegate void SimpleDelegate();
public SimpleDelegate onFrame;
Your constructor would become this: 您的构造函数将变为:
public GameObject (SimpleDelegate of)
{
onFrame = of;
Thread t = new Thread(runOnFrame);
t.isBackgroundThread = true;
t.Start();
}
Then later, something like this: 然后,如下所示:
GameObject G1 = new GameObject(new SimpleDelegate(() => {
i++;
}));
..... .....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.