3

在我的 .NET 类中,我通过 .NET 访问我的属性和成员this。如果我在不使用this.

public class Test
{
    private string _test;

    public Test()
    {
        this.Test = "test";
        // vs. 
        Test = "test";

        // and
        this._test = "test";
        // vs. 
        _test = "test";
    }

    public string Test { get; set; }
}
4

8 回答 8

2

编译器根本没有区别。使用更具可读性的内容。我更喜欢用this它来表明这是一个字段/属性而不是局部变量。

于 2012-12-18T10:11:01.590 回答
2

This只是指类的变量。当您尝试时,它可以避免您被绊倒:

private string Test;

public Test(String Test)
{
    this.Test = Test;
    // vs. 
    Test = Test;

}

第一个将正常工作。

于 2012-12-18T10:12:38.540 回答
1

在你有同名的参数之前,这并没有什么区别

public class Test
{
 private string _test;

 public Test(string Test,string _test)
 {
    this.Test = "test";//this refers invoking object Test i.e class varaible
    // vs. 
    Test = "test";//this refer method passed Test param

    // and
    this._test = "test";//this refers invoking object Test i.e class varaible
    // vs. 
    _test = "test";//this refer method passed Test param
}

  public string Test { get; set; }
}

所以在上面的案例方法参数测试隐藏类测试参数,为了避免这种情况,你需要使用它来引用类的当前对象

于 2012-12-18T10:12:31.737 回答
0

您的代码没有区别,但有时this可以帮助您指定范围。

public Test(string _test)
{
    this._test = "test"; // sets class field
    // vs. 
    _test = "test"; // sets ctor parameter
}
于 2012-12-18T10:10:48.870 回答
0

就最终结果而言,没有区别。

一件事是,键入此内容将为您提供智能感知,仅列出该类中可用的成员。

此外,如果该方法是类的扩展方法,那么您将需要使用它来调用它。

于 2012-12-18T10:11:06.120 回答
0

用不用没区别this。这只是关于可读性。

于 2012-12-18T10:11:14.873 回答
0

查看 msdn 页面: http: //msdn.microsoft.com/en-us/library/dk1507sz (v=vs.80).aspx

在 C#this中,主要用于在变量和参数具有相同名称时增加可读性。

于 2012-12-18T10:13:10.930 回答
0

编译器没有区别。使用对您来说更具可读性。

public class Test 
{ 

private string _test;

public Test(string Test)
{
    this.Test = "test";
    // vs. 
    Test = "test";

    // and
    this._test = "test";
    // vs. 
    _test = "test";
}

  public string Test { get; set; }
}
于 2012-12-18T10:14:25.157 回答