简体   繁体   English

C#类实例

[英]C# Class instance

I'm a beginner in programming and I've read several tutorials. 我是编程的初学者,我已经阅读了几个教程。 I'm still unclear about the following: 我还不清楚以下内容:

When clicking on a button, that event creates an instance of a class: 单击按钮时,该事件会创建一个类的实例:

private void button2_Click(object sender, RoutedEventArgs e)
{
    int a = 1;
    myClass test = new myClass(a);
}

myClass is doing a long processing job (several minutes). myClass正在做一个很长的处理工作(几分钟)。 If I click 5 times on my button, is it gonna create 5 instances? 如果我在按钮上单击5次,是否会创建5个实例? Or is the "test" going to be "overwritten" 4 times? 或者“测试”将被“覆盖”4次?

Thanks 谢谢

If I click 5 times on my button, is it gonna create 5 instances ? 如果我在按钮上单击5次,是否会创建5个实例? Or the "test" instance will be "overwritten" 4 times ? 或者“测试”实例将被“覆盖”4次?

Yes its going to create 5 separate instances. 是的,它将创建5个单独的实例。 You are creating an object that immediately falls out of scope after it is constructed, so the next time a different instance of the same class is constructed. 您正在创建一个在构造之后立即超出范围的对象,因此下次构造同一个类的不同实例时。

I assume you were planning to do the processing as part of your constructor, keep in mind this will block the UI thread, your program will "freeze" - if you are looking to do a long processing job, you shouldn't do it on the UI thread - look into ie the BackgroundWorker . 我假设您计划将处理作为构造函数的一部分,请记住这将阻止UI线程,您的程序将“冻结” - 如果您要执行长时间的处理工作,则不应该执行此操作UI线程 - 查看即BackgroundWorker

It will create however many instances that you click. 它会创建您单击的许多实例。 However, if the work is synchronous and blocks the UI thread you can't click it again until the work has completed. 但是,如果工作是同步的并阻止UI线程,则在工作完成之前无法再次单击它。 If your work is asynchronous it will create a new instance every time you click. 如果您的工作是异步的,则每次单击时都会创建一个新实例。

Instead try... 相反,试试......

private myClass _test;
private void button2_Click(object sender, RoutedEventArgs e)
{
    int a = 1;

    if (_test == null)
    {
        _test = new myClass(a);
    }
}

Though, I would not recommend doing synchronous work on the UI thread. 虽然,我不建议在UI线程上进行同步工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM