Creating a new instance of an object when a button is clicked

It seems like it should be fairly simple, but I am having trouble moving my brain around it. You typically declare an object in one of two ways.

ClassName a;
a = new ClassName();

or

ClassName a = new ClassName();

etc...

but since you explicitly declare them at compile time, I am embarrassed when Im should code this at runtime. What I want to do is a new instance of the class created at the click of a button. But I donโ€™t understand how the name of the object will be called if this happens when the button is pressed?

+3
source share
4 answers

, .
, naimg, .

, , :

void ButtonClick_H1(...)
{
  ClassName a;          //local variable
  a = new ClassName();  // object belongs to this method
}


private  ClassName anObject;   // class field
void ButtonClick_H2(...)
{ 
  anObject = new ClassName();  // object belongs to  'this' Form
}
+5
public partial class Form1
{
    Classname myClass;

    public void Button1_Click(...)
    {
          myClass = new Classname();
    }
}

?

+2

, , , . , ( ), , , .

+1

, .

Click:

this.Button.Click += new RoutedEventHandler(Button_Click);

-

private void Button_Click(object sender, RoutedEventArgs e)
{
    ClassName a = new ClassName();
}
+1

Source: https://habr.com/ru/post/1773543/


All Articles