编写this.propertyName或只是propertyName之间的区别

时间:2014-04-13 09:20:32

标签: c# constructor

我正在查看编写类的示例并使用构造函数,并且想知道使用"这是什么区别。"或不。

那么:

之间的区别是什么?
public class PagedCountryList
{
    public IEnumerable<Country> CountriesToDisplay { get; set; }
    public int Total { get; set; }
    public int PerPage { get; set; }
    public int PageNumber { get; set; }

    public PagedCountryList(IEnumerable<Country> countries, int totalResult, int elementsPerPage, int pageNumber)
    {
        this.CountriesToDisplay = countries;
        this.Total = totalResult;
        this.PerPage = elementsPerPage;
        this.PageNumber = pageNumber;
    }
}

而且:

public class PagedCountryList
{
    public IEnumerable<Country> CountriesToDisplay { get; set; }
    public int Total { get; set; }
    public int PerPage { get; set; }
    public int PageNumber { get; set; }

    public PagedCountryList(IEnumerable<Country> countries, int totalResult, int elementsPerPage, int pageNumber)
    {
        CountriesToDisplay = countries;
        Total = totalResult;
        PerPage = elementsPerPage;
        PageNumber = pageNumber;
    }
}

4 个答案:

答案 0 :(得分:4)

您的情况没有差异,但请考虑此示例

public class PagedCountryList
{
    private IEnumerable<Country> countries { get; set; }
    public int totalResult { get; set; }
    public int elementsPerPage { get; set; }
    public int pageNumber { get; set; }

    public PagedCountryList(IEnumerable<Country> countries, int totalResult, int elementsPerPage, int pageNumber)
    {
       //you cant write something like this (because it is ambiguous)
       //countries = countries;
        this.countries = countries;
        this.totalResult = totalResult;
        this.elementsPerPage = elementsPerPage;
        this.pageNumber = pageNumber;
    }
}

答案 1 :(得分:4)

实际上你的情况没有区别。以下是MSDN

中描述的this的常见用法
  • 限定以类似名称隐藏的成员
  • 将对象作为参数传递给其他方法
  • 申报指数

答案 2 :(得分:2)

正如汤姆所说,在这种情况下,“这个”是多余的,但这并不意味着你不应该使用它。

您的会员“public int Total”可以使用“this”直接访问,也可以不使用。另一方面,如果你使用Total作为函数参数,你需要用“this”来区分它是否是函数参数的类成员

function SetTotal(int Total)
{
this.Total = Total;
}

答案 3 :(得分:1)

在你的情况下,没有区别。这是对自己的引用。 它是有用的,在某些情况下,你在同一范围内&#34;重复命名变量&#34;。