相关疑难解决方法(0)

你什么时候使用"this"关键字?

我很好奇其他人如何使用this关键字.我倾向于在构造函数中使用它,但我也可以在其他方法中使用它.一些例子:

在构造函数中:

public Light(Vector v)
{
    this.dir = new Vector(v);
}
Run Code Online (Sandbox Code Playgroud)

别处

public void SomeMethod()
{
    Vector vec = new Vector();
    double d = (vec * vec) - (this.radius * this.radius);
}
Run Code Online (Sandbox Code Playgroud)

c# coding-style this

248
推荐指数
11
解决办法
19万
查看次数

C#何时使用"此"关键字

可能重复:
您何时使用"this"关键字?

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

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"; …
Run Code Online (Sandbox Code Playgroud)

c# constructor this

25
推荐指数
3
解决办法
4万
查看次数

标签 统计

c# ×2

this ×2

coding-style ×1

constructor ×1