Proper usage of “this.” keyword in C#?

末鹿安然 提交于 2019-12-23 02:31:49

问题


I'm working through the book Head First C# (and it's going well so far), but I'm having a lot of trouble wrapping my head around the syntax involved with using the "this." keyword.

Conceptually, I get that I'm supposed to use it to avoid having a parameter mask a field of the same name, but I'm having trouble actually tracking it through their examples (also, they don't seem to have a section dedicated to that particular keyword, they just explain it and start using it in their examples).

Does anyone have any good rules of thumb they follow when applying "this."? Or any tutorials online that explain it in a different way that Head First C#?

Thanks!


回答1:


Personally I only use it when I have to which is:

  • Constructor chaining:

    public Foo(int x) : this(x, null)
    {
    }
    
    public Foo(int x, string name)
    {
        ...
    }
    
  • Copying from a parameter name into a field (not as common in C# as in Java, as you'd usually use a property - but common in constructors)

    public void SetName(string name)
    {
        // Just "name = name" would be no-op; within this method,
        // "name" refers to the parameter, not the field
        this.name = name;
    }
    
  • Referring to this object without any members involved:

    Console.WriteLine(this);
    
  • Declaring an extension method:

    public static TimeSpan Days(this int days)
    {
        return TimeSpan.FromDays(days);
    }
    

Some other people always use it (e.g. for other method calls) - personally I find that clutters things up a bit.




回答2:


StyleCop's default coding style enforces the following rule:

A1101: The call to {method or property name} must begin with the 'this.' prefix to indicate that the item is a member of the class.

Which means that every method, field, property that belongs to the current class will be prefixed by this. I was initially resistant to this rule, which makes your code more verbose, but it has grown on me since, as it makes the code pretty clear. This thread discusses the question.




回答3:


I write this. if and only if it enhances readability, for example, when implementing a Comparable interface (Java, but the idea is the same):

public void compareTo(MyClass other) {
  if (this.someField > other.someField) return 1;
  if (this.someField < other.someField) return -1;
  return 0;
}

As to parameter shadowing (e.g. in constructors): I usually give those a shorter name of the corresponding field, such as:

class Rect {
  private int width, height;
  public Rect(int w, int h) {
    width = w;
    height = h;
  }
}



回答4:


Basically, this gives you a reference to the current object. You can use it to access members on the object, or to pass the current object as parameters into other methods.

It is entirely unnecessary in almost all cases to place it before accessing member variables or method calls, although some style guidelines recommend it for various reasons.

Personally, I make sure I name my member variables to be clearly different from my parameters to avoid ever having to use 'this.'. For example:

private String _someData;
public String SomeData
{
    get{return _someData;}
    set{_someData = value;}
}

It's very much an individual preference though, and some people will recommend that you name the property and member variable the same (just case difference - 'someData' and 'SomeData') and use the this keyword when accessing the private member to indicate the difference.

So as for a rule of thumb - Avoid using it. If you find yourself using it to distinguish between local/parameters variables and member variables then rename one of them so you don't have to use 'this'.

The cases where I would use it are multiple constructors, passing a reference to other methods and in extension methods. (See Jon's answer for examples)




回答5:


If you have a method inside a class which uses same class's fields, you can use this.

public class FullName
    {
        public string fn { set; get; }
        public string sn { set; get; }

        //overriding Equals method
        public override bool Equals(object obj)
        {
            if (!(obj is FullName))
                return false;

            if (obj == null)
                return false;

            return this.fn == ((FullName)obj).fn &&
            this.sn == ((FullName)obj).sn;
        }

        //overriding GetHashCode
        public override int GetHashCode()
        {
            return this.fn.GetHashCode() ^ this.sn.GetHashCode(); 
        }
    }


来源:https://stackoverflow.com/questions/2307115/proper-usage-of-this-keyword-in-c

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