When to use THIS keyword when working with controls on form in C#

走远了吗. 提交于 2019-12-10 14:12:21

问题


I am still far away from mastering C#, but the child in me is pushing me to continue improving my programming day by day.
When I make a WinForms application I want to change and use lot of controls pragmatically.
What I do not understand is when I need to use the this.control keyword and when I should use just control.
Sample:
If I want to change the text of my label I can write

mylabel.text = "Text for label"

or

this.mylabel.tex = "Text for label"

Which of these is the right way? Is there a simple explanation when to use the this keyword when using controls in WinForms (such as datagrid, text, tables, etc.)?


回答1:


In this case, both of those lines are "correct". However, the use of "this" is not needed here.

One reason to use "this" is if you need to resolve an ambiguity. "this" gives you unambiguous access to the members of a class. Here's an example:

class Test
{
   public void SetNumber(int number)
   {
      this.number = number;
   }

   private int number;
}

In this example, you must use "this" to refer to the class member "number" and assign to it the value in the passed in argument with the same name ("number").

Of course, it would be better to have a naming convention that prevents this. I tend to put an underscore in front of private member data (ie. _number).




回答2:


It's only strictly necessary when you are diambiguating between a field/property and a local variable. Others prefer to use it in other places, but that's a style decision.



来源:https://stackoverflow.com/questions/3428459/when-to-use-this-keyword-when-working-with-controls-on-form-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!