C#"对象引用未设置为对象的实例"获取类型/获取属性

时间:2016-07-03 18:46:57

标签: c# winforms object gettype getproperty

大家好我收到错误:"对象引用没有设置为对象的实例"。我不太清楚为什么......以下是代码:

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),

1 个答案:

答案 0 :(得分:0)

您正在尝试获取查询的类型,然后获取该类型的“显示”属性,而不是数据库中列的返回值

查询的类型不具有属性“display”。你需要做更多的事情:

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

string details = property.Name;

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

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