0

我目前正在审查用 c# 编写的代码,Visual Studio 2012。

在很多地方,代码都是使用这个关键字编写的,例如:

this.pnlPhoneBasicDtls.Visible = true;
this.SetPhAggStats(oStats);

还有许多其他地方使用此关键字来引用页面的控件。

有人可以建议我们真的需要在这里使用它吗?删除此关键字的任何后果?

提前致谢..

4

3 回答 3

4

不,“这个”是可选的。它通常包含在由工具生成的代码中,以及那些认为需要明确或想要将其与方法的参数区分开来的人。

于 2013-10-07T07:10:40.090 回答
2

它是可选的,您可以使用

Property directly like   pnlPhoneBasicDtls.Visible = true;
于 2013-10-07T07:14:08.423 回答
0

The this keyword is usually optional.

It's sometimes used to disambiguate fields from arguments if the same name is being used for both, for example:

void Main()
{
    var sc = new SomeClass();
    sc.SomeMethod(123);
    Console.WriteLine(sc.thing);
}

public class SomeClass
{
    public int thing;

    public void SomeMethod(int thing)
    {
        this.thing = thing + 1;
    }
}

In the example above it does make a difference. Inside SomeMethod, this.thing refers to the field and thing refers to the argument.

(Note that the simpler assignment thing = thing is picked up as a compiler error, since it is a no-op.)

Of course, if you use ReSharper then any unnecessary this. (together with unused using statements, unreachable code, etc.) will be greyed out and you can remove them very quickly. The same is probably true of similar tools like CodeRush.

于 2013-10-07T07:32:51.413 回答