簡體   English   中英

用void類型定義類屬性(不是方法)

[英]Defining a class property with type void (not a method)

我正在嘗試建立一個名為GameObject的類(用於consoleApplication游戲),並且GameObject應該具有一個名為“ onFrame”的函數,比方說,每0.1秒調用一次。

但是要注意的是,對於每個gameObject來說,該函數(void)應該是唯一的-假設我有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
        }
    }
}

和主要功能:

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!");
    })
}

但這似乎不是正確的方法……可能嗎? 我該怎么做?

您正在尋找的是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();
        }
    }
}

但是,我建議使用Timer而不是在連續循環中調用thread.Sleep

傳遞委托的一種方法是使用lambda語法:

GameObject G1 = new GameObject(() => i++ );

()是空輸入參數集的占位符:

您需要的是一名代表。

您的“ onFrame”定義應如下所示:

public delegate void SimpleDelegate();
public SimpleDelegate onFrame;

您的構造函數將變為:

public GameObject (SimpleDelegate of)
{
    onFrame = of;
    Thread t = new Thread(runOnFrame);
    t.isBackgroundThread = true;
    t.Start();
}

然后,如下所示:

GameObject G1 = new GameObject(new SimpleDelegate(() => {
    i++;
}));

.....

暫無
暫無

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

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