简体   繁体   中英

In C#, is accessing the current object's properties through this.XYZ considered poor style compared to just XYZ

这是仅不使用this.XYZ构造的简单情况吗?

It's only considered poor style if it violates your style guidelines. Sometimes using this is necessary to qualify a member variable over a local variable:

public MyType(int arg)
{
    this.arg = arg;
}

This problem can also be mitigated with style guidelines. For example, prefix members with "_":

public MyType(int arg)
{
    _arg = arg;
}

I wouldn't say it's poor style - but it's not particularly idiomatic.

My almost sole use of this.foo is when copying parameters into fields:

public Person (string name, string occupation)
{
   this.name = name;
   this.occupation = occupation;
}

I've never heard of it being a style issue. I used to do it all the time to get intellisense, but then I started using ctrl-j, then I just found myself remembering my object's properties without having to use a crutch.

Probably because my objects have become less complex as I gain more experience...

I always use this. for global variable. This way, I can clearly know that I am using a global variable without having to use prefix like "_".

MS工具StyleCop在分析源代码时坚持使用this.XYZ(或应为this.Xyz)变体。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM