有谁知道我在做什么错为什么委托没有在我的代码中工作? 我有一个控制台应用程序,它在开始时显示一个表单,并使用委托更新表单中的标签。.Net委托不工作
namespace DELEGATESAMPLEPROJECT
{
public class Program
{
public delegate void OnConfirmCall();
public OnConfirmCall confirmCall;
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1(new Program().getReference()));
new Program().startFunctionCall();
}
public Program getReference(){
return this;
}
public void startFunctionCall(){
Console.WriteLine("Function Call Started!");
if(confirmCall != null){
Console.WriteLine("Function Call Executing...");
confirmCall();
}
}
}
}
FORM1
namespace DELEGATESAMPLEPROJECT
{
public partial class Form1 : Form
{
public Form1(Program thisProgramClass)
{
InitializeComponent();
thisProgramClass.confirmCall += saySomething;
}
public void saySomething()
{
Label1.Text = "Hello World!";
}
private void Form1_Load(object sender, EventArgs e)
{
Label1.Text = "Hi C#!";
}
}
}
,你可以看到,我试图改变"Hi C#!"
到"Hello World!"
但其没有工作,我很想念?
因为您使用了两个完全不同的'Program'实例。这里'Application.Run(new Form1(new Program()。getReference())); '和'new Program()。startFunctionCall();'这里。 –
@ChristophKn请将其作为回答发布 – slawekwin
@ ChristophKn - 我应该重命名程序类吗? – bernzkie