从链表 C# 的元素引用 class' 函数

Referencing class' function from an element of a linked list C#

为了我的大学项目,我需要实现一个循环链表,其中包含一些特定元素。问题:我希望链表的一个元素有一个指向创建它的 class 中的函数的指针。在伪 C# 中显示问题:

using System;
class Game{
    internal void state1(){
        Console.WriteLine("Executing state1 code");
    }
    internal void state2(){
        Console.WriteLine("Executing state1 code");
    }
Element elem1 = new Elem(state1);
Element elem2 = new Elem(state2);
elem1.Call();
elem2.Call();
}

class Element{
    FunctionPointer Call = null;
    Element(FunctionPointer function){
        Call = function;
    }
}

我试过使用委托,但不太正确。是否可以使用接口以某种方式实现此目的?

我的代表尝试:

using System;
public delegate void MyDelegate();

class Game{
    internal void state1(){
        Console.WriteLine("Executing state1 code");
    }
    internal void state2(){
        Console.WriteLine("Executing state1 code");
    }
    Element elem = new Element(new MyDelegate(state1));
}

class Element{
    MyDelegate functionPointer = null;
    Element(MyDelegate func){
        functionPointer =  func;
    }
}

有几种方法可以做到这一点。使用委托就像...

public class Game
{
    private Element _element = null;

    public Game()
    {
        _element = new Element(state1);
    }
    internal void state1()
    {
        Console.WriteLine("Executing state1 code");
    }
    internal void state2()
    {
        Console.WriteLine("Executing state2 code");
    }
}

public class Element
{
    public delegate void FunctionPointer();
    private FunctionPointer _function = null;

    public Element(FunctionPointer function)
    {
        _function = new FunctionPointer(function);
        _function();            
    }
}

使用界面...

public interface IGame
{
    void state1();
    void state2();
}
public class Game : IGame
{
    private Element _element = null;

    public Game()
    {
        _element = new Element(this);
    }
    public void state1()
    {
        Console.WriteLine("Executing state1 code");
    }
    public void state2()
    {
        Console.WriteLine("Executing state1 code");
    }
}

public class Element
{
    private IGame _game = null;

    public Element(IGame game)
    {
        _game = game;
        _game.state1();
    }
}

我认为界面更好