C#如何传递函数,在别的类中执行

Taotesea 2012-12-30 10:41:02
例如:
public class a
{
b b1=new b();
public void a1()
{
MessageBox.Show("a1");
}

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

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

在这里先谢谢大家了!
...全文
365 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
你的选择B 2012-12-30
  • 打赏
  • 举报
回复
针对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();
        }
    }
  • 打赏
  • 举报
回复
事件是一种傻瓜化的简单封装,非常清晰地说明了软件设计中需要的编程接口概念。我们编程当然是越傻瓜越好,越有“成文自明的规范越好”。事件驱动的概念的自然而然的含义,傻瓜程序员都体会得到的,因此应该首先这样设计。
  • 打赏
  • 举报
回复
对于初学者,不要“设计”诡异的代码。如果你还是停留在设计简单系统的水平上,先把各种基本的模式(例如事件驱动机制)使用好。 建议你至少6、7年以后再搞这些。
owennol 2012-12-30
  • 打赏
  • 举报
回复
用委托,加A1作为参数传入到B类中
enaking 2012-12-30
  • 打赏
  • 举报
回复
你应该多去看看委托 public class a { b b1=new b(() => a1()); public void a1() { MessageBox.Show("a1"); } public class b { public b(Action func) { func(); } }
threenewbee 2012-12-30
  • 打赏
  • 举报
回复
使用委托 public class a { b b1=new b(() => a1()); public void a1() { MessageBox.Show("a1"); } public class b { public b(Action func) { func(); } }
Taotesea 2012-12-30
  • 打赏
  • 举报
回复
谢谢大家:)

110,536

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧