.Net代表不工作

时间:2016-09-26 06:46:49

标签: c# .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!",但它不起作用,我缺少什么?

2 个答案:

答案 0 :(得分:3)

namespace DELEGATESAMPLEPROJECT
{
  public class Program
  {
    public delegate void OnConfirmCall();
    public OnConfirmCall confirmCall;

    [STAThread]
    static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);

        var programRef = new Program().getReference(); // <- only one reference.

        Application.Run(new Form1(programRef)); //Start the form1

        programRef.startFunctionCall();//Call this function to change the Label in Form1
    }

    public Program getReference(){
        return this;
    }

    public void startFunctionCall(){
        Console.WriteLine("Function Call Started!"); //Write this to confirm the function is called
        if(confirmCall != null){
            Console.WriteLine("Function Call Executing...");//Write this to confirm that the delegate is working
            confirmCall();
        }
    }
}

答案 1 :(得分:2)

好吧,您正在使用Program课程的两个实例。我看到你正在尝试做什么,但实例化两种形式会让他们互相愚蠢。他们彼此不认识,所以你的confirmCall代表将无效。

解决这个问题很容易。

由于OP希望将实例分配给全局字段。我们这样宣布它。另请注意,我们已经删除了GetReference Program方法,而不需要这样做。

private static Program programInstance = new Program();

通过这样做,您将获得Program课程的一个实例,并将其传递给您的Form1,可以在您的表单类中使用。

Form1 form = new Form1(programInstance);
Application.Run(form);

这样,您只有一个实例。但是IMO你可以在这种情况下使用SingleTon模式,如果你真的只需要一个实例。

作为单身人士的参考,我建议调查Jon Skeet博客关于Singleton pattern

相关问题