重载的ToString不会出现在intellisense中

时间:2016-07-31 13:16:22

标签: c# .net delegates

我在youtube处接受了教程。在8:04,讲师附加了本地方法来重载ToString,当我尝试做同样的事情时,我没有看到intellisense中的重载方法。

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

我尝试添加关键字覆盖它也不起作用。看起来像我在某处遗漏了某些东西。

1 个答案:

答案 0 :(得分: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.
}

while:

foreach(var p in PersonListBox.Items.OfType<Person>())

提示:您也可以使用 async void MessageReceived(DatagramSocket socket, DatagramSocketMessageReceivedEventArgs eventArguments) { uint stringLength = eventArguments.GetDataReader().UnconsumedBufferLength; string receivedMessage = eventArguments.GetDataReader().ReadString(stringLength); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { MessageOutput.Text += (receivedMessage + "\n"); }); }