2014-04-13 43 views
1

我正在看編寫一個類的例子,並使用構造函數,並想知道使用「this」的區別是什麼。或不。寫this.propertyName或只是propertyName之間的區別

那麼,什麼是之間的differnce:

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

沒有差別。 '這個。'在這種情況下是多餘的 –

+1

如果您的構造函數使用與您的屬性相同的參數,那麼將需要'this'。 –

+0

感謝您的快速解答! – user3228992

回答

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

在你的情況,沒有任何區別。這是對你自己的一個參考。 有用的是在同一範圍內有「重複命名的變量」的情況。

2

湯姆認爲,在這種情況下「本」是多餘的,但是,這並不意味着你should'n使用它。

您的會員「public int Total」可以直接用「this」或不用。在如果您已使用總計爲函數參數另一方面,你需要區分是否是函數參數的類成員用「這個」

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

其實,有你的情況沒有什麼區別。下面是this的常見用途從MSDN

  • 描繪要符合成員通過類似名稱
  • 隱藏要傳遞一個對象作爲參數傳遞給其他方法
  • 要聲明索引
相關問題