从链表C#的元素中引用类的函数

时间:2018-11-18 12:27:28

标签: c# delegates function-pointers

出于我的大学项目的目的,我需要实现一个包含一些特定元素的循环链接列表。问题:我希望链接列表中的元素具有指向创建它的类中的函数的指针。要显示伪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;
    }
}

1 个答案:

答案 0 :(得分:0)

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

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();
    }
}

我认为界面更好