使用动态方法创建类

时间:2016-05-29 04:54:38

标签: c# delegates runtime

所以我基本上要做的是在C#中创建一个动态菜单框架。我基本上有一个菜单元素(此时只是一个矩形,上面有一些文字),它包含一个DoAction()方法。单击矩形时将运行此方法。我想要的是能够在运行时定义DoAction方法。因此,例如,我可以实例化一个菜单元素,其DoAction()方法的函数是x(),然后实例化另一个菜单元素,其DoAction()方法的函数为y()。我所拥有的是这样的。

public class MenuElement {
    public void DoAction(); // method I want to be dynamic

    public MenuElement((text, height, width, etc), method myMethod){
        DoAction = myMethod;
    }
}

MenuElement m1 = new MenuElement(..., function x());
MenuElement m2 = new MenuElement(..., function y());

m1.DoAction(); // calls x()
m2.DoAction(); // calls y()

这是我知道如何在Javascript中做的事情,但我不熟悉C#,我怀疑.Net会让我跳过比JS更多的箍。从我正在阅读的内容中我将不得不使用代表?我找不到任何我可以轻松遵循的教程。

2 个答案:

答案 0 :(得分:2)

使用Action-Class。在您的示例中,它将是:

public class MenuElement {
public Action DoAction; // method I want to be dynamic

public MenuElement((text, height, width, etc), Action myMethod){
    DoAction = myMethod;
}
}

MenuElement m1 = new MenuElement(..., new Action(() => {
// your code here
});

MenuElement m2 = new MenuElement(..., new Action(() => {
// your code here
));

m1.DoAction(); // calls x()
m2.DoAction(); // calls y()

有关详细信息,请参阅MSDN

答案 1 :(得分:1)

是的,代表们可以走了。您可以根据需要使用代表ActionFunc的不同风格。这是你想要实现的目标吗?

public class MenuElement
{
    public MenuElement(string text, int height, int width, Action<object> myMethod)
    {
        DoAction = myMethod;
    }

    public Action<object> DoAction { get; private set; }
}

        MenuElement m1 = new MenuElement("text", 10, 20, (obj) => { Console.WriteLine("MenuElement1"); });
        m1.DoAction(null);


        Action<object> y = (obj) =>
        {
            Console.WriteLine("MenuElement2");
        };

        MenuElement m2 = new MenuElement("text", 10, 20, y);
        m2.DoAction(null); // calls y()
相关问题