C# 何时使用“This”关键字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/843288/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 03:50:25  来源:igfitidea点击:

C# When To Use "This" Keyword

c#constructorthis

提问by Goober

Possible Duplicate:
When do you use the “this” keyword?

可能的重复:
您什么时候使用“this”关键字?

Hello, I understand that the Thiskeyword is used to refer to an instance of the class, however, suppose I have a class called Life, which defines two fields, the person (their name) and their partner(their name):

您好,我知道This关键字用于引用类的实例,但是,假设我有一个名为 的类Life,它定义了两个字段,人员(他们的姓名)和他们的合作伙伴(他们的姓名):

class Life
{
    //Fields
    private string _person;
    private string _partner;

    //Properties
    public string Person
    {
        get { return _person; }
        set { _person = value; }
    }

    public string Partner
    {
        get { return _partner; }
        set { _partner = value; }
    }

    //Constructor 1
    public Life()
    {
        _person = "Dave";
        _partner = "Sarah";

        MessageBox.Show("Life Constructor Called");
    }

    //Constructor 2
    public Life()
    {
        this._person = "Dave";
        this._partner = "Sarah";

        MessageBox.Show("Life Constructor Called");
    }
}

Is there a difference between constructor 1 and constructor 2!? Or is it just better coding practice to use the "This" keyword?

构造函数1和构造函数2有区别吗!?还是使用“This”关键字只是更好的编码实践?

Regards

问候

采纳答案by tvanfosson

The constructors are the same. The reason I would prefer the second is that it will allow you to remove the underscores from your private variable names and retain the context (improving understandability). I make it a practice to always use thiswhen referring to instance variables and properties.

构造函数是一样的。 我更喜欢第二个的原因是它允许您从私有变量名称中删除下划线并保留上下文(提高可理解性)。this在引用实例变量和属性时,我习惯于始终使用它。

I no longer use the thiskeyword in this way after moving to a different company with different standards. I've gotten used to it and now rarely use it at all when referring to instance members. I do still recommend using properties (obviously).

this搬到不同标准的不同公司后,我不再以这种方式使用关键字。我已经习惯了,现在在提到实例成员时很少使用它。我仍然建议使用属性(显然)。

My version of your class:

我的课程版本:

class Life
{
    //Fields
    private string person;
    private string partner;

    //Properties
    public string Person
    {
        get { return this.person; }
        set { this.person = value; }
    }

    public string Partner
    {
        get { return this.partner; }
        set { this.partner = value; }
    }


    public Life()
    {
        this.person = "Dave";
        this.partner = "Sarah";

        MessageBox.Show("Life Constructor Called");
    }
}

or, even better, but not as clear about the use of thiswith fields.

或者,甚至更好,但不清楚thiswith 字段的使用。

class Life
{

    //Properties
    public string Person { get; set; }
    public string Partner { get; set; }

    public Life()
    {
        this.Person = "Dave";
        this.Partner = "Sarah";

        MessageBox.Show("Life Constructor Called");
    }
}

回答by Richard

You can use this to differentiate between a local variable named X and a class level field/property of the same name.

您可以使用它来区分名为 X 的局部变量和同名的类级别字段/属性。

回答by Brian ONeil

There is no difference in the two statements...

两种说法没有区别...

//These are exactly the same.

this._person 

//and 

_person 

The reference to "this" is implied in the case of _person. I wouldn't say that it is necessarily "better" coding practice, I would say that it is just preference.

在 _person 的情况下暗示了对“this”的引用。我不会说它一定是“更好”的编码实践,我会说这只是偏好。

回答by hmcclungiii

You shouldn't be using the private variables _person and _parter. That is the purpose of your getters and setters.

您不应该使用私有变量 _person 和 _parter。这就是你的 getter 和 setter 的目的。

As far as the constructs, there is no real difference between them. That being said, I always prefer to use the This keyword as it lends towards readability.

就构造而言,它们之间没有真正的区别。话虽如此,我总是更喜欢使用 This 关键字,因为它有助于提高可读性。

回答by Marc Gravell

Since you are using underscores, there is no conflict between the names; so the "this." is redundant and can be omitted. The IL will be unaffected.

由于您使用下划线,因此名称之间没有冲突;所以“ this.”是多余的,可以省略。IL 将不受影响。

As long as there is no ambiguity between a field and variable/parareter, there is only one scenario in which the thiskeyword (in the context of meaning the current instance - not ctor-chaining) is strictly necessary - invoking an extension method that is defined separately:

只要字段和变量/参数之间没有歧义,只有一种情况下this关键字(在当前实例的上下文中 - 不是构造函数链)是绝对必要的 - 调用定义的扩展方法分别地:

this.SomeExtensionMethod();  // works
SomeExtensionMethod();  // fails

回答by Peter Lillevold

"this" is also used in .Net 3.5 with extension methods:

“this”也在 .Net 3.5 中使用扩展方法:

public static class MyExtensions
{    
    public static string Extend(this string text)
    {
       return text + " world";
    }
}

would extend the string class

将扩展字符串类

var text = "Hello";
text.Extend();

To answer your question: no, there is no difference in your two constructors. Imo, the "this" clutters the code and should only be used when necessary, e.g. when parameters and field variables have the same names.

回答您的问题:不,您的两个构造函数没有区别。Imo,“this”使代码混乱,只应在必要时使用,例如当参数和字段变量具有相同的名称时。

There is also a case when the class explicitly implements an interface. If you need to call the interface methods from within your class you would have to cast this to the interface:

还有一种情况是类显式实现了接口。如果您需要从类中调用接口方法,则必须将其强制转换为接口:

class Impl : IFace
{

    public void DoStuff()
    {
        ((IFace)this).SomeMethod();
    }

    void IFace.SomeMethod()
    {
    }
}

回答by Hannoun Yassir

Both constructors do the same thing anyway in the second one the thisis redundant

无论如何,两个构造函数在第二个构造函数中都做同样的事情,这this是多余的