开发者

Foo() vs this.Foo() [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. 开发者_开发百科 Closed 11 years ago.

I have a co-worker who uses a C# refactoring tool. The tool for some reason perfers:

this.Foo()

over

Foo()

Now we've asked him to turn it off simply because it's annoying to have all the code re-written automatically, but that's not the point.

Am I missing something, or is this just wrong? Why on earth would I want this.Foo()?


As other answers here point out, this is largely a matter of style.

Many times a call to Foo() would be unambiguous without the this., but there are times where it might add clarity. For example:

EventHandler foo = GetEventHandlerFoo();
EventHandler baz = GetEventHandlerBar();
foo();
this.Bar();
baz();

In this case, the this. prefix helps to make the method invocation stand out from the delegate invocations.

Is this necessary? No, and Lasse V. Karlsen correctly points out that the this. is just a surrogate for a naming convention that makes it unambiguous.

But I find that I will frequently use the this.Foo prefix on local properties for a similar reason, where again it is more a matter of style.


If you want to use it, use it.

If you don't want to use it, don't use it.

There's no right answer here.

If for some reason you have a naming convention where the name alone isn't enough to determine whether you're looking at a local variable, a method parameter, an instance field, a property, or a method, you should fix the naming convention, instead of prefixing local fields with this. to distinguish them from local variables.


I think this comes down to a question of syntax vs. semantics. The argument for this.Foo() is it very explicitly denotes exactly what Foo() is and where it came from. There's no wondering if it was an argument passed in to a method, or a static class declared who-knows-where. It's a method on the current object, period. Anything less and you're giving up clear semantics in favor of tighter syntax.

The obvious argument against it: Mouse-over and ctrl+click.


It's a style thing. Sometimes people think it makes the code more clear -- apparently some people find it helpful to be explicit about the target of a method invocation. Personally, I find the spurious use of this to be distracting.


This example demonstrates how the this keyword can be used to explicitly describe a variable's scope:

class Item
{
    int id;

    public Item (int id)
    {
        this.id = id;
    }

}


I always use this. since it explicitly shows where the thing is. I don't even use a refactoring tool to do it. I type it by hand.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜