C# "Object reference not set to an instance of an object" 获取类型/获取 属性

C# "Object reference not set to an instance of an object" Get Type / Get Property

大家好,我收到一条错误消息:"Object reference not set to an instance of an object"。我不太清楚为什么...这是代码:

public void LoadUserContacts(ListBox FriendsLb)
{
   FriendsLb.DisplayMember = "Display";
   var query = from o in Globals.DB.Friends
               where o.UserEmail == Properties.Settings.Default.Email
               select new
               {
                   FirstName = o.FirstName,
                   LastName = o.LastName,
                   Email = o.Email,
                   Display = string.Format("{0} {1} - ({2})", o.FirstName, o.LastName, o.Email),
                };
   FriendsLb.DrawMode = DrawMode.OwnerDrawVariable;

   foreach (object contact in query.ToList())
   {
       string details = query.GetType().GetProperty("Display").ToString();
       FriendsLb.Items.Add(new Contacts(Properties.Resources.avatar, details));
       FriendsLb.DrawItem += FriendsLb_DrawItem;
       FriendsLb.MeasureItem += FriendsLb_MeasureItem;
    }
}

导致错误的代码:

string details = query.GetType().GetProperty("Display").ToString();

有什么想法吗?我正在尝试从查询中获取显示 属性:

Display = string.Format("{0} {1} - ({2})", o.FirstName, o.LastName, o.Email),

您正在尝试获取查询的类型,然后是该类型"Display"的属性,而不是数据库中列的return值

查询的类型不会有属性"display"。您需要做更多类似的事情:

string property = contact.GetProperty("Display", typeof(string));

string details = property.Name;

我希望它能让你走上正轨。

此外,在该行设置断点以查看该行的哪一部分是空引用,以便轻松查明问题所在。