使用void类型(不是方法)定义类属性

Yot*_*mon 1 c# oop void

我正在尝试构建一个名为GameObject的类(用于consoleApplication游戏),GameObject应该有一个函数"onFrame",每0.1秒调用一次.

但问题是,这个函数(void)应该对每个gameObject都是唯一的 - 假设我有GameObject:G1,G2.G1会在onFrame中将变量增加1,G2会在控制台上打印一些内容(只是示例).

有可能吗?

我试着用这种方式做到这一点:

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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

主要功能:

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!");
    })
}
Run Code Online (Sandbox Code Playgroud)

但它似乎不是正确的方式......这可能吗?我该怎么做?

D S*_*ley 6

您正在寻找的是一个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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但是我建议使用a Timer而不是thread.Sleep连续循环调用.

传递委托的一种方法是使用lambda语法:

GameObject G1 = new GameObject(() => i++ );
Run Code Online (Sandbox Code Playgroud)

()是一个空输入参数集的占位符:

  • `onFrame`不应该是`Action <int>`类型吗? (2认同)