何时何地使用“this”关键字

时间:2011-03-16 09:03:33

标签: c# this keyword

  

可能重复:
  When do you use the “this” keyword?

大家好,

我只是想知道何时何地使用关键字必须?因为有时如果我不“这个”甚至我删除“这个”程序运行正常。那么如果你不使用它会发生什么?或者如果你在错误的地方使用它。

一些明确的例子会受到批评。

8 个答案:

答案 0 :(得分:3)

this关键字通常用于消除成员变量和局部变量之间的歧义:

...
{
    int variable = 10;

    this.variable = 1; // modifies a member variable.

    variable = 1; // modifies the local variable.
}
....

this的另一个用途是传递对当前对象的引用,所以:

....
DoSomethingWithAnObject( this );
....

另一种用法(感谢HadleyHope)是将方法参数分配给具有相同名称的成员变量时消除歧义:

void Initialise( int variable )
{ 
    this.variable = variable;
}

答案 1 :(得分:1)

调用静态成员时不能使用它。编译器不会让你。当您使用“this”时,您将显式调用当前实例。我喜欢用“this”为当前实例成员添加前缀,即使这不是强制性的,只是为了清楚起见。这样我就将局部范围变量与成员区分开来。

干杯

答案 2 :(得分:1)

public class People{
    private String name;
    private int age;
    public People(String name, int age){
        this.name = name;
        this.age = age; //use this to declare that the age is the field in People class 
    }
}

使用此方法的一种方法,希望它可以帮助您。

答案 3 :(得分:1)

Microsoft建议将camelCase用于成员变量,即

public class MyClass
{
     private int myInt;

     private void SetMyInt(int myInt)
     {
          this.myInt = myInt;
     }
}

因此,如果您没有'this'关键字,私有成员和参数之间就会出现混淆。

就个人而言,我更喜欢在私人成员前加上下划线以避免这种混淆。

private int _myInt;

所以我找到的唯一真正用途是将当前对象的引用传递给其他东西

MyStaticClass.MyStaticMethod(this);

答案 4 :(得分:0)

您不必每次在成员方法中使用“this”关键字,在这种情况下它很有用:

class human
{
    private int age;
...
    void func(int age)
    {
       this.age = age;
    }
...
}

它可以解决你所说年龄的混乱

答案 5 :(得分:0)

当你在同一个范围内有一个成员变量和一个同名的局部变量时,你可以使用它 - 然后“this”将清楚你的意思。

考虑一下:

class Person
{
    private string name;

    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }

    public Person(string name)
    {
        this.name = name;   // "this" is necessary here to disambiguate between the name passed in and the name field.
        this.Name = name;   // "this" is not necessary, as there is only one Name in scope.
        Name = name;        // See - works without "this".
    }
}

答案 6 :(得分:0)

每当我访问成员变量或方法时,我个人都会使用这个。 99%的时间没有必要,但我认为它提高了清晰度并使代码更具可读性 - 一个质量非常值得输入4个字符和一个点的额外工作。

答案 7 :(得分:0)

这有点主观,但如果您使用正确的命名约定(我使用_camelCase作为成员变量),您将永远不需要使用this

除了这个例外:=)

如果要从扩展方法所针对的类中调用扩展方法:

public class HomeController : Controller
{

    public ActionResult Index()
    {
        // won't work
        return MyCustomResult();
    }

    public ActionResult List()
    {
        // will work
        return this.MyCustomResult();
    }
}

public static class MyExtensions
{
    public static MyResult MyCustomResult(this Controller instance)
    {
         return new SomeResult(instance.ActionName);
    }
}
相关问题