2016-07-31 24 views
0

我正在瀏覽教程youtube。在8:04指導員將本地方法附加到重載的ToString,當我嘗試做同樣的事情時,我在intellisense中看不到重載的方法。重載的ToString未出現在智能感知中

enter image description here

public class Person 
    { 
     public string FirstName { get; set; } 
     public string LastName { get; set; } 
     public DateTime StartDate { get; set; } 
     public int Rating { get; set; } 

     public override string ToString() 
     { 
      return string.Format("{0} {1}", FirstName, LastName); 
     } 

     public string ToString(PersonFormat format) 
     { 
      return format(this); 
     } 

我嘗試添加關鍵字覆蓋太不work.Looks像我的地方失去了一些東西。

回答

0

這是因爲var隱藏了person的實際類型,當通過PersonListBox.Items訪問時,它是對象。以下作品:

foreach(Person person in PersonListBox.Items) 
{ 


} 

雖然:

foreach(var person in PersonListBox.Items) 
{ 
    // person is object. It doesn't have the method you want to call. 
    // it even doesn't have FirstName or LastName 
    // try person. and you can clearly see it only has the common 
    // object methods. 
} 

提示:您還可以使用foreach(var p in PersonListBox.Items.OfType<Person>())

+0

謝謝!它確實有用! – Noob

+0

@ user3185569:接受!非常感謝 ! – Noob