正确使用"this". C#中的关键字? [英] Proper usage of "this." keyword in C#?
问题描述
我正在阅读《 Head First C#》一书(到目前为止进展顺利),但是在使用"this"所涉及的语法时,我遇到了很多麻烦.关键字.
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).
在应用"this"时,有人遵循任何良好的经验法则吗?还是任何在线教程以与Head First C#不同的方式解释它?
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#?
谢谢!
推荐答案
我个人仅在需要的时候使用它:
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)
{
...
}
从参数名称复制到字段中(在C#中不像在Java中那样常见,因为您通常会使用属性-但在构造函数中很常见)
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.
这篇关于正确使用"this". C#中的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!