Understanding C# Events use of sender object

后端 未结 5 1061
时光说笑
时光说笑 2020-12-09 14:07

I am reasonably new to C# as a language (coming from a C++ background) and I am currently in the process of writing an application that makes use of an event driven API.

5条回答
  •  一整个雨季
    2020-12-09 14:56

    When parameters are passed by reference,

    1. The properties present inside the reference instance can be change without affecting the original reference instance.

    2. Original reference can be changed using the ref keyword.

    The following is an example

    public partial class ParentForm : Form
    {
        public ParentForm()
        {
            InitializeComponent();
            ChildForm childForm = new ChildForm();
            ChangeCaption( childForm );
            //Will display the dialog with the changed caption.
            childForm.ShowDialog();
            ChangeCaption( ref childForm );
            //Will give error as it is null
            childForm.ShowDialog();
        }
    
        void ChangeCaption( ChildForm formParam )
        {
            // This will change openForm’s display text
            formParam.Text = "From name has now been changed";
            // No effect on openForm
            formParam = null;                        
        }
    
    
        void ChangeCaption( ref ChildForm formParam )
        {
            // This will change openForm’s display text
            formParam.Text = "From name has now been changed";
            // This will destroy the openForm variable!
            formParam = null;                        
        }
    }
    

提交回复
热议问题