c# - 写this.propertyName或只是propertyName之间的区别

标签 c# constructor

我正在看一个编写类并使用构造函数的示例,并想知道使用“ this”的区别是什么。或不。

那么,两者之间有什么区别?

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;
    }
}

最佳答案

您的情况没有区别,但请考虑以下示例

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;
    }
}

关于c# - 写this.propertyName或只是propertyName之间的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23040968/

相关文章:

c# - 使用 linqtoexcel 从 excel 文件中获取所有值

c# - 数据库脚手架在 .Net Core 1.1 中停止工作

java - 定义构造函数类并初始化值

c# - 从 VS 2012 升级到 VS 2013 后 WebServices 不工作

c# - 如何在 ASP.NET MVC 中为项目编写良好的核心架构

c# - WPF WrapPanel - 所有项目都应具有相同的宽度

c# - 我的共享插件构造函数有什么问题?

c++ - 如何使用非平凡构造函数构造静态 thread_local 成员

go - 存储所有符合相同接口(interface)的类型的构造函数集合

c++ - 来自元组的构造函数参数