例如这样
class B
{
void dosth
{}
}
class A
{
B b
void do
{}
}b是B类的实例,是A的一个成员。现在希望在b.dosth()中,调用其外部的A.do(),可否做到?如何做到?
class B
{
void dosth
{}
}
class A
{
B b
void do
{}
}b是B类的实例,是A的一个成员。现在希望在b.dosth()中,调用其外部的A.do(),可否做到?如何做到?
调试欢乐多
{
void dosth
{
A a= NEW A();
a.do();
}
}
public class A
{
B b
public void do()
{}
}
class B :A
{
void dosth
{
a.do();
}
}
class A
{
B b
void do
{}
}
因此在类B代码里面没法定义A的实例……我想了一下,貌似是不可能完成任务啊。
调用要使用一个关键字this
我是希望B中某函数能够改变其外部类A(form1)中的某控件。
public event Test EventTest;
class B
{
void dosth()
{
if(EventTest!=null)
{
EventTest();
}
}
} class A
{
//在A的构造中订阅B事件
B b ;
public A()
{
b.EventTest+=this.do;
}
void do ()
{}
} 这样不就在B的doSth方法执行的时候,触发了A中的事件处理程序吗?不知道行不行
public delegate void Test();
public event Test EventTest;
要放在哪里呢?又需要改动什么?
我把9楼的代码copy过去后,把
public delegate void Test();
public event Test EventTest;
放到了class B里面,却在
b.EventTest+=this.do;这里提示do无法隐式的转换为void。
public class B
{
public event test etest; public void DoSth()
{
if (etest != null)
{
etest();
}
}
}
public partial class Form1 : Form
{
B b = new B(); public Form1()
{
b.etest += this.b_etest;
InitializeComponent();
b.DoSth(); } void b_etest()
{
//这里就执行了,当然也可以从别的地方出发b.DoSth()
} }
using System.Collections.Generic;
using System.Text;
namespace CS2
{
public class Class1
{
public delegate void Test();
public event Test EventTest;
public void show()
{
EventTest();
}
}
}以上为要封装的class1using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;namespace CS2
{
public partial class Form1 : Form
{
public Class1 myclass1 = new Class1();
public Form1()
{
InitializeComponent();
myclass1.EventTest += this.showd();
myclass1.show();
}
public void showd()
{
MessageBox.Show ("OK");
}
}
}以上为需要调用class1的窗体。这只是一个测试。即,希望class1执行show()中的代码时,能够使form1执行showd()。
{
//这里就执行了,当然也可以从别的地方出发b.DoSth()
}
void改为Test
并在末尾return null。
我确定我在15楼说的是事实。感觉delegate就像是注册了一个类Test一样。