日期:2014-05-17  浏览次数:21123 次

C#如何传递函数,在别的类中执行
例如:
public class a
{
b b1=new b();
public void a1()
{
MessageBox.Show("a1");
}

//如何将A1函数传递给B类中,并且在B类中执行A1这个函数
}

public class b
{
.......
}

在这里先谢谢大家了!

------解决方案--------------------
使用委托
public class a
{
b b1=new b(() => a1());
public void a1()
{
MessageBox.Show("a1");
}

public class b
{
    public b(Action func) { func(); }
}
------解决方案--------------------
你应该多去看看委托
public class a
{
b b1=new b(() => a1());
public void a1()
{
MessageBox.Show("a1");
}

public class b
{
    public b(Action func) { func(); }
}
------解决方案--------------------
用委托,加A1作为参数传入到B类中
------解决方案--------------------
对于初学者,不要“设计”诡异的代码。如果你还是停留在设计简单系统的水平上,先把各种基本的模式(例如事件驱动机制)使用好。

建议你至少6、7年以后再搞这些。
------解决方案--------------------
事件是一种傻瓜化的简单封装,非常清晰地说明了软件设计中需要的编程接口概念。我们编程当然是越傻瓜越好,越有“成文自明的规范越好”。事件驱动的概念的自然而然的含义,傻瓜程序员都体会得到的,因此应该首先这样设计。
------解决方案--------------------
针对LZ的需求有两种方法:
1:将a中的a1定义成静态的,b中直接调用即可

    public class a
    {
        b b1 = new b();
        public static void a1()
        {
            MessageBox.Show("a1");
        }

        //如何将A1函数传递给B类中,并且在B类中执行A1这个函数
    }

    public class b
    {
        public static void Test()
        {
            //这里直接调用
            a.a1();
        }
    }

2:使用委托

    public class a
    {
        b b1 = new b();
        public void a1()
        {
            MessageBox.Show("a1");
        }

        //如何将A1函数传递给B类中,并且在B类中执行A1这个函数
    }

    public class b
    {

        public void TestOther()
        {
            Action action = new a().a1;
            action();